Submitting multipart/form-data using jQuery and Ajax

It is possible to submit files using "multipart/form-data" and ajax. There are many sites out there that show complicated ways of doing this when it is really easy. It simply requires a little configuration of the jquery ajax process and grabbing your form data using the FormData() function.

Using the following method, you can submit multiple files and are not just limited to one.

Lets take a look at our form.

<form id="data">
  <input type="hidden" name="id" value="123" readonly="readonly">
  User Name: <input type="text" name="username" value=""><br />
  Profile Image: <input name="profileImg[]" type="file" /><br />
  Display Image: <input name="displayImg[]" type="file" /><br />
  <input type="submit" value="Submit">
</form>

The above form has a hidden field, a user name field, and then two file image fields that we are going to submit to our PHP processing page.

Now lets look at the jQuery used to submit the form using "multipart/form-data" and ajax.

//Program a custom submit function for the form
$("form#data").submit(function(event){
 
  //disable the default form submission
  event.preventDefault();
 
  //grab all form data  
  var formData = new FormData($(this)[0]);
 
  $.ajax({
    url: 'formprocessing.php',
    type: 'POST',
    data: formData,
    async: false,
    cache: false,
    contentType: false,
    processData: false,
    success: function (returndata) {
      alert(returndata);
    }
  });
 
  return false;
});

That is all that is needed to submit your "multipart/form-data" form to a PHP processing page using ajax. You would call your form data on the processing page like normal.

$id = $_POST['id'];
$username = $_POST['username'];
$profileImg = $_FILES['profileImg'];
$displayImg = $_FILES['displayImg'];

Comments

You can get the original name of the file from the respective $_FILES variable.

Example: $_FILES['userfile']['name'] - The original name of the file on the client machine.

See: http://php.net/manual/en/features.file-upload.post-method.php

can you give me the php code of above filebecause i got only the file array not the other data of the form

Thank you very much. It work perfectly. :)

Man, you are the best

Any way to display the upload progress during the upload...?

Pages