Home > Web Front-end > JS Tutorial > How to Implement AJAX File Upload with FormData Using Drag and Drop?

How to Implement AJAX File Upload with FormData Using Drag and Drop?

Barbara Streisand
Release: 2024-12-18 20:37:11
Original
608 people have browsed it

How to Implement AJAX File Upload with FormData Using Drag and Drop?

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>
Copy after login

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);
    }
  });
});
Copy after login

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);
    Copy after login
  • Alternatively, specify specific data to FormData():

    var formData = new FormData();
    formData.append('file', $('input[type=file]')[0].files[0]);
    Copy after login

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.
});
Copy after login

Note:

  • Type "POST" in options is necessary as all files must be sent via POST request.
  • contentType: false is only available in jQuery version 1.6 and onwards.

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!

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template