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">

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
  //disable the default form submission
  //grab all form data  
  var formData = new FormData($(this)[0]);
    url: 'formprocessing.php',
    type: 'POST',
    data: formData,
    async: false,
    cache: false,
    contentType: false,
    processData: false,
    success: function (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'];


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.


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...?