Home >Web Front-end >JS Tutorial >How Can I Use FormData for Asynchronous AJAX File Uploads with jQuery?

How Can I Use FormData for Asynchronous AJAX File Uploads with jQuery?

Linda Hamilton
Linda HamiltonOriginal
2024-12-12 21:42:14504browse

How Can I Use FormData for Asynchronous AJAX File Uploads with jQuery?

Using FormData for Asynchronous AJAX File Uploads

To leverage FormData for AJAX file uploads, crucial steps are involved.

Preparations

Utilize jQuery's first form element to feed the FormData() for processing:

var form = $('form')[0]; // Use standard JavaScript object
var formData = new FormData(form);

Alternatively, select specific data for FormData():

var formData = new FormData();
formData.append('section', 'general');
formData.append('action', 'previewImg');
formData.append('image', $('input[type=file]')[0].files[0]); // Attach file

Sending the Form

Craft the Ajax request using jQuery:

$.ajax({
    url: 'Your url here',
    data: formData,
    type: 'POST',
    contentType: false, // Essential, do not omit (from jQuery 1.6+)
    processData: false, // Essential, do not omit
    // ... Other options like success, etc.
});

This request will submit the data like a regular form with "multipart/form-data" encoding.

Note:

  • "Type: 'POST'" is mandatory, as file transmissions necessitate POST requests.
  • "contentType: false" is available only from jQuery 1.6 onwards.

The above is the detailed content of How Can I Use FormData for Asynchronous AJAX File Uploads with jQuery?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn