AJAX File Upload with FormData
Problem:
Using FormData for file upload in an AJAX request with dynamic HTML generated using drag and drop functionality.
HTML Code:
<form>
JavaScript Code:
$('.wpc_contact').submit(function(event) { var form = $('.wpc_contact').serialize(); var formname = $('.wpc_contact').attr('name'); var FormData = new FormData($(form)[1]); $.ajax({ url: '<?php echo plugins_url(); ?>/wpc-contact-form/resources/js/tinymce.php', data: { form: form, formname: formname, FormData: FormData }, type: 'POST', processData: false, contentType: false, success: function(data) { alert(data); } }); });
Solution:
To correctly use FormData, follow these steps:
1. Preparation:
Use the standard JavaScript object 'form' to pass the entire form to FormData():
var form = $('form')[0]; var formData = new FormData(form);
Alternatively, specify specific data to FormData():
var formData = new FormData(); formData.append('file', $('input[type=file]')[0].files[0]);
2. Sending the Form:
Use jQuery AJAX request with these options:
$.ajax({ url: 'Your url here', data: formData, type: 'POST', contentType: false, // Required processData: false, // Required // ... Other options like success, etc. });
Note:
The above is the detailed content of How to Implement AJAX File Upload with FormData Using Drag and Drop?. For more information, please follow other related articles on the PHP Chinese website!