How to Send Both File and String Data with FormData() and jQuery AJAX?

Mary-Kate Olsen
Release: 2024-10-22 14:39:02
Original
884 people have browsed it

How to Send Both File and String Data with FormData() and jQuery AJAX?

Posting Both File and String Data with FormData() and jQuery AJAX

It is often necessary to send both file and input string data through AJAX requests. To achieve this using FormData(), follow these steps:

  1. Create a FormData Object:

    <code class="js">var fd = new FormData();</code>
    Copy after login
  2. Append File Data:
    a. For a single file:

    <code class="js">fd.append("file", file_data);</code>
    Copy after login

    b. For multiple files:

    <code class="js">var file_data = $('input[type="file"]')[0].files; // for multiple files
    for(var i = 0;i<file_data.length;i++){
        fd.append("file_"+i, file_data[i]);
    }</code>
    Copy after login
  3. Append String Data:

    <code class="js">var other_data = $('form').serializeArray();
    $.each(other_data,function(key,input){
        fd.append(input.name,input.value);
    });</code>
    Copy after login
  4. Send Data with AJAX:

    <code class="js">$.ajax({
        url: 'url',
        data: fd,
        contentType: false,
        processData: false,
        type: 'POST',
        success: function(data){
            alert(data);
        }
    });</code>
    Copy after login

By following these steps, you can send both file and input string data within the same FormData object and AJAX request.

The above is the detailed content of How to Send Both File and String Data with FormData() and jQuery AJAX?. For more information, please follow other related articles on the PHP Chinese website!

source:php
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
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!