unknown_111 unknown_111 - 4 months ago 21x
Javascript Question

Send multiple file attachments to php file using ajax

I have the following html code inside a form:

<input type="file" id="attachments" name="attachments" multiple>

I already have a javascript function that handles the onsubmit for the form using ajax but without handling the uploaded files.

This is the part of my javascript function that sends the data to the required php file:

var to_users = $("#to_users").val();
var title = $("#title").val();
var content = $("#content").val();

var data = {

$.ajax({url: "submit.php", type:"POST" , data:data ,success: function(result){

// does something

There are many tutorials and questions online about attachments using ajax and php but none of them handles multiple files.
My question is: what do I need to add to this function so that I send the attached files to the php file ? And what should I write in the php file in order to handle the files it receives?


To upload multiple images use array:

<input type="file" id="attachments" name="attachments[]" multiple>

and send the form data using ajax:

 var formData = new FormData(this);
    url: "submit.php",
    type: "POST",
    data: formData,
    processData: false,
    contentType: false,
    success: function(result){

    // do something

In php file use a loop( foreach i recommend) to save all attachments.

foreach($_FILES['attachments']['name'] as $key=>$val){

// do whatever you want