jQuery $.ajax function is quiet a nifty way to post data within a form to any URL without refreshing the page and so is used extensively wherever jQuery is used. A typical jQuery $.ajax function looks like:

		$.ajax({
				type: 'POST',
				url: this/is/your/post/url,
				data: form_data,
				dataType: 'json',
				cache: false,
				contentType: false,
				processData: false,
				success: function(result) {
					console.log(result);
				},
				error: function(result){
					console.log(result);
				}
		});

More information about the $.ajax function and it’s options can be found on the jQuery API Documentation page at http://api.jquery.com/jquery.ajax/

Now, there are several ways by which one can post all the data in a form using ajax. I’m going to discuss some of the most common and most easy ways as per me, in no particular order.

First, lets have a simple form as an example:

      <form id="testform" class="form-ajax" enctype="multipart/form-data">
		Name: <input type="text" name="name"/><br>
		Email: <input type="email" name="email"/><br>
		Phone: <input type="number" name="phone"/><br>
		Vehicle:<br>
		<input type="checkbox" name="vehicle1" value="Bike"> I have a bike<br>
		<input type="checkbox" name="vehicle2" value="Car"> I have a car<br>
		Select Car:
		<select name="car">
		  <option value="noCar">No Car</option>
		  <option value="volvo">Volvo</option>
		  <option value="saab">Saab</option>
		  <option value="opel">Opel</option>
		  <option value="audi">Audi</option>
		</select><br>
		Select your favorite color: <input type="color" name="favcolor"><br>
		Birthday (date and time): <input type="datetime-local" name="bdaytime"><br>
		<input type="hidden" name="country" value="America"><br>
		Password: <input type="password" name="pwd"><br>
		Gender:<br>
		<input type="radio" name="gender" value="male"> Male<br>
		<input type="radio" name="gender" value="female"> Female<br>
		<input type="radio" name="gender" value="other"> Other<br>
		<input type="file" name="fileone"/><br>
		<input type="file" name="filetwo"/><br>
		<input type="file" name="filethree"/><br>
		<a href="javascript:void(0)" class="btn btn-primary" id="submit">Submit</a>
	</form>

This will create a form like below:

Name:
Email:
Phone:
Vehicle:
I have a bike
I have a car
Select Car:

Select your favorite color:
Birthday (date and time):

Password:
Gender:
Male
Female
Other



Submit

I have taken all ‘types’ of input fields that are used commonly. You’ll notice that I have taken three type=’file’ fields, that’s because if we only have to attach just one file we can also do it in a different way but the method I use for attaching multiple files can be used for single files as well.

    Number 1 (My Favorite)

The first method I’m going to discuss is my favorite because of it’s simplicity and compactness. In this method we create an object of the FormData Class and post the data in one go.

	$("#submit").click(function(){
        var url = "<?php echo $_SERVER['PHP_SELF']; ?>";

		var form = document.getElementById('testform');
		var files = $("#testform input[type=\'file\']"); // Getting the properties of files from file fields
		
		var filesData = [];
		
		for(i in files){
			if(!isNaN(i)){
				filesData.push(files[i]['files'][0]);
			}			
		}
				
		var form_data = new FormData(form); // Creating object of FormData class
			form_data.append("files", filesData);
	
		$.ajax({
				type: 'POST',
				url: url,
				data: form_data,
				dataType: 'json',
				cache: false,
				contentType: false,
				processData: false,
				success: function(result) {
					console.log(result);
				},
				error: function(result){
					console.log(result);
				}
		});
	});

In this method all the types of input except the type file is posted and received in the $_POST super global variable. Therefore to attach the files we first get the properties of all the files from the file fields. As these properties contain a lot of data that we don’t need, we iterate the data using a for… in… loop and save the required files info in a new array. We then append that array to the newly created FormData object. This FormData object is then posted via the $.ajax function within the ‘data’ settings object. Note that in this method the ‘name’ attribute of the input field will be the ‘key’ for the $_POST array, for example, when the below field is posted:

you can get it’s value on the server side using $_POST[‘phone’].

As you can see, this method is fairly simple, self explanatory and quite compact.

    Number 2 – Get all input types

Another useful method is also quiet popular, for reasons unknown to me. But still it needs to be discussed. In this method we wrap all our form fields inside a div for the sake of simplicity and simply assign all the ‘inputs’ value within that div to a variable and post that in the ‘data’. Checking out below will make more sense.

first we wrap our form fields inside a div tag like:

      <form id="testform" class="form-ajax" enctype="multipart/form-data">
          <div id="testform-div">
		Name: <input type="text" name="name"/><br>
		Email: <input type="email" name="email"/><br>
		Phone: <input type="number" name="phone"/><br>
		Vehicle:<br>
		<input type="checkbox" name="vehicle1" value="Bike"> I have a bike<br>
		<input type="checkbox" name="vehicle2" value="Car"> I have a car<br>
		Select Car:
		<select name="car">
		  <option value="noCar">No Car</option>
		  <option value="volvo">Volvo</option>
		  <option value="saab">Saab</option>
		  <option value="opel">Opel</option>
		  <option value="audi">Audi</option>
		</select><br>
		Select your favorite color: <input type="color" name="favcolor"><br>
		Birthday (date and time): <input type="datetime-local" name="bdaytime"><br>
		<input type="hidden" name="country" value="America"><br>
		Password: <input type="password" name="pwd"><br>
		Gender:<br>
		<input type="radio" name="gender" value="male"> Male<br>
		<input type="radio" name="gender" value="female"> Female<br>
		<input type="radio" name="gender" value="other"> Other<br>
		<input type="file" name="fileone"/><br>
		<input type="file" name="filetwo"/><br>
		<input type="file" name="filethree"/><br>
		<a href="javascript:void(0)" class="btn btn-primary" id="submit">Submit</a>
           </div>
	</form>

As you can see, all the fields are inside the div with the id “testform-div”. Now for our ajax part:

	$("#submit").click(function(){
        var url = "<?php echo $_SERVER['PHP_SELF']; ?>";

		$.ajax({
				type: 'POST',
				url: url,
				data: $('#testform-div input[type=\'text\'], #testform-div input[type=\'password\'], #testform-div input[type=\'color\'], #testform-div input[type=\'number\'], #testform-div input[type=\'date\'], #testform-div input[type=\'datetime-local\'], #testform-div input[type=\'time\'], #testform-div input[type=\'checkbox\']:checked, #testform-div input[type=\'radio\']:checked, #testform-div input[type=\'hidden\'], #testform-div textarea, #testform-div select'),
				dataType: 'json',
				cache: false,
				contentType: false,
				processData: true,
				success: function(result) {
					console.log(result);
				},
				error: function(result){
					console.log(result);
				}
		});
	});

Apart from the obvious ajax ‘data:’ field value, also notice the value of the ‘processData’ ajax field, it should be either set to true or should be omitted all together as its default value is true. The processData option when true means that the ‘data passed in to the data option as an object (technically, anything other than a string) will be processed and transformed into a query string, fitting to the default content-type “application/x-www-form-urlencoded”.’, as per the jqueryAjax documentation, which means that the parameters or the input name and values would be converted into a string and sent along in the URL. This can mean security flaw in some cases. Other than this, as far as I know, there isn’t a way to post or upload files using this method. So, I don’t know why this method is popular but may be someone can shed a light on it.

    Number 3 – The traditional way

The third method is the traditional way. You take all the values of fields and create an object and then pass that object on to the ajax ‘data:’ option. This method might be lengthy but it’s the most reliable and also it gives you the ability to change the name or keys of the $_POST array variable to your own choice. On the downside this method also doesn’t allow you to post or upload files and also has to ‘processData’. So, now for this method our ajax code looks like:

	$("#submit").click(function(){
        var url = "<?php echo $_SERVER['PHP_SELF']; ?>";

        var formObject = {
			'full_name' : $('#testform-div input[name=\'name\']').val(),
			'email' : $('#testform-div input[name=\'email\']').val(),
			'phone_number' : $('#testform-div input[name=\'phone\']').val(),
			'vehicle_one' : $('#testform-div input[name=\'vehicle1\']:checked').val(),
			'vehicle_two' : $('#testform-div input[name=\'vehicle2\']:checked').val(),
			'car_maker' : $('#testform-div select[name=\'car\']').val(),
			'color' : $('#testform-div input[name=\'favcolor\']').val(),
			'bdaytime' : $('#testform-div input[name=\'bdaytime\']').val(),
			'country' : $('#testform-div input[name=\'country\']').val(),
			'password' : $('#testform-div input[name=\'pwd\']').val(),
			'gender' : $('#testform-div input[name=\'gender\']:checked').val()			
		};

		$.ajax({
				type: 'POST',
				url: url,
				data: formObject,
				dataType: 'json',
				cache: false,
				contentType: true,
				processData: true,
				success: function(result) {
					console.log(result);
				},
				error: function(result){
					console.log(result);
				}
		});
	});

Notice the keys of the ‘formOject’ has been changed as per my liking. These keys would be received as the keys in the $_POST array in the PHP code. Also, notice that in this method too we have to either omit the processData and the contentType options or set them as ‘true’ for this to work.

As you can see, the first method is the best among the discussed as it’s more secure and also allows to upload files as well. I’m sure there are numerous other ways to upload files and post data using ajax and I would love to hear all of them out. Feel free to comment anything that you might wanna discuss, share or if just wanna say hi 🙂

That’s all.

Happy Coding 🙂

Leave a Reply

Your email address will not be published. Required fields are marked *