Home  >  Article  >  Backend Development  >  How to Send Both File and String Data with FormData() and jQuery AJAX?

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

Mary-Kate Olsen
Mary-Kate OlsenOriginal
2024-10-22 14:39:02892browse

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>
  2. Append File Data:
    a. For a single file:

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

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

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!

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