What I am attempting to accomplish here is to create a separate ajax request for each file being uploaded. I have an ajax call that creates a record and returns some html and the tempID of a record that is used by an ajax call which executes on success of the first call. This process appears to be functioning correctly. Where the problem is arising is the loop through the filesList. Before the ajax calls the loop appears to be working fine, but during the ajax call when I'm expecting the files list to increment to the next file in the array it is sending the first file again.
If I only select a single file then everything works correctly. It is as if the ajax calls do not see that the variable "file" is being reset at the beginning of the loop when there are multiple files....got me stumped...
/* Fire the ajax requests when the input files array changes
--------------------------------------------------------------------------*/
$('#theFile').on('change', function()
{
var len = this.files.length;
for(var i = 0; i < len; i++)
{
var file = this.files[i];
// console.log(file.name); This shows the correct file name
var formData = new FormData();
formData.append("file_" + i, file);
$.ajax(
{
url: '/controllerName/buildImageLoadingDIVS',
type: 'POST',
dataType:'json',
data: 'fileName=' + file.name,
success: function(data1)
{
$('#theImages').append(data1.content);
formData.append("tempID", data1.tempID);
// console.log(file.name);
// This shows the first filename in the array as if
// variable "file" was never set to new filelist
$.ajax(
{
url: '/controllerName/the_image_upload',
type: 'POST',
data: formData,
processData: false,
contentType: false,
success: function(data2)
{
$('#temp_wrapper_' + data1.tempID).html(data2);
}
});
}
});
}