Home >Web Front-end >JS Tutorial >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:
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!