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:
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!