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
Barbara StreisandOriginal
2024-12-18 20:37:11611browse

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>

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:

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

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