Search code examples
jqueryajaxresponse

Merge multiple ajax responses in one array


I have implemented dropzone.js in one website. When I drop multiple files in a div, dropzone.js sends one request at a time which is good for php performance and file upload limit.

However the downside of it is that I could not figure out how to catch all responses and merge them in a single array. In my array I can only save the value of the last response.

Here is my code:

$("#dropzoneJs").dropzone({
  maxFiles: 2000,
  success: function(file, response) {
    var array = [];
    $.each(response, function() {
      $.each(this, function(k, v) {
        v = response.data.image;
        console.log(v);
        array.push(v);
      });
    });

    var array1 = JSON.stringify(array);
    $('#fdata').val(array1);
  }
});

I dragged two different files and when i save the two responses in an array i get only the last response in that array multiplied by two times.

["/images/aluguer/1.jpg","/images/aluguer/1.jpg"]

What i need is:

["/images/aluguer/1.jpg","/images/aluguer/2.jpg"]

Console.log output (don't mind red errors they are not related):

enter image description here


Solution

  • You need to declare the array outside the function, otherwise you're starting from an empty array each time it's used.

    var dropZoneArray = [];
    
    $("#dropzoneJs").dropzone({
      maxFiles: 2000,
      success: function(file, response) {
        $.each(response, function() {
          $.each(this, function(k, v) {
            v = response.data.image;
            console.log(v);
            dropZoneArray.push(v);
          });
        });
    
        var array1 = JSON.stringify(dropZoneArray);
        $('#fdata').val(array1);
      }
    });