Search code examples
javascriptajaxarraysform-data

appending array to FormData and send via AJAX


I'm using ajax to submit a multipart form with array, text fields and files.

I append each VAR to the main data as so

var attachments = document.getElementById('files'); 
var data= new FormData();

for (i=0; i< attachments.files.length; i++){
    data.append('file', attachments.files[i]);
    console.log(attachments.files[i]);

    data.append ('headline', headline);
    data.append ('article', article);
    data.append ('arr', arr);
    data.append ('tag', tag);

then I use the ajax function to send it to a PHP file to store inside sql DB.

$.ajax({    
    type: "post",
    url: 'php/submittionform.php',
    cache: false,
    processData: false,
    contentType: false,
    data: data,
    success: function(request) {$('#box').html(request); }
})

But on the PHP side, the arr variable, which is an array appears as a string.

When I don't send it with ajax as Form data but use the simple $.POST option I do get it as an array on the PHP side, but then I can't send the files as well.

any solutions?


Solution

  • You have several options:

    Convert it to a JSON string, then parse it in PHP (recommended)

    JS

    var json_arr = JSON.stringify(arr);
    

    PHP

    $arr = json_decode($_POST['arr']);
    

    Or use @Curios's method

    Sending an array via FormData.


    Not recommended: Serialize the data with, then deserialize in PHP

    JS

    // Use <#> or any other delimiter you want
    var serial_arr = arr.join("<#>"); 
    

    PHP

    $arr = explode("<#>", $_POST['arr']);