Home >Web Front-end >JS Tutorial >How to Correctly Use FormData for AJAX File Uploads with jQuery?

How to Correctly Use FormData for AJAX File Uploads with jQuery?

Mary-Kate Olsen
Mary-Kate OlsenOriginal
2024-12-15 17:42:14632browse

How to Correctly Use FormData for AJAX File Uploads with jQuery?

Using FormData for AJAX File Upload

In this scenario, you're attempting to implement AJAX file upload using a drag-and-drop generated HTML form. However, your current JavaScript implementation requires adjustments to correctly utilize the FormData object for file upload.

Preparations

Firstly, create the FormData object:

var form = $('form')[0]; // For the entire form
var formData = new FormData(form);

Alternatively, you can specify specific data to include:

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

Sending the Form

Next, update your jQuery AJAX request to include the following settings:

$.ajax({
    url: 'Your url here',
    data: formData,
    **type: 'POST', // Use POST requests for file upload**
    contentType: false, // Important for file upload
    processData: false, // Important for file upload
    // ... Other options like success and etc
});

These settings ensure that the form data is sent correctly as a multipart/form-data request, which is essential for file uploads.

Additional Note:

  • contentType: false is only available in jQuery 1.6 onwards.
  • The type: 'POST' setting is crucial because file uploads require POST requests.

The above is the detailed content of How to Correctly Use FormData for 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