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

Susan Sarandon
Release: 2024-10-22 14:27:02
Original
584 people have browsed it

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

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

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

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

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

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

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

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

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!

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!