Home  >  Article  >  Backend Development  >  How to Simultaneously Transmit FormData and String Data Using JQuery AJAX?

How to Simultaneously Transmit FormData and String Data Using JQuery AJAX?

Susan Sarandon
Susan SarandonOriginal
2024-10-22 14:27:02592browse

How to Simultaneously Transmit FormData and String Data Using JQuery AJAX?

Simultaneous Transmission of FormData and String Data Using JQuery AJAX

To send both file and string data using FormData(), consider the following approach:

Create a new FormData object:

<code class="javascript">var fd = new FormData();</code>

For multiple files, retrieve the selected files from the file input:

<code class="javascript">var file_data = $('input[type="file"]')[0].files;</code>

Loop through the files and append them to the FormData using a unique name for each file:

<code class="javascript">for(var i = 0;i<file_data.length;i++){
    fd.append("file_"+i, file_data[i]);
}</code>

Next, retrieve the non-file input data using jQuery's .serializeArray():

<code class="javascript">var other_data = $('form').serializeArray();</code>

Iterate through the non-file input data and append it to the FormData using .append():

<code class="javascript">$.each(other_data,function(key,input){
    fd.append(input.name,input.value);
});</code>

Finally, configure the AJAX request with the FormData as the data payload:

<code class="javascript">$.ajax({
    url: 'test.php',
    data: fd,
    contentType: false,
    processData: false,
    type: 'POST',
    success: function(data){
        console.log(data);
    }
});</code>

By following these steps, you can effectively send both file and string data simultaneously through FormData and JQuery AJAX, ensuring that all necessary information is transmitted to the server.

The above is the detailed content of How to Simultaneously Transmit FormData and String Data Using 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