I would like to chain an asynchronous ajax function that is called several times within a loop. Why? Because that function is to upload files but I want it to serially upload files rather than uploading all of them at once. I don't want to use async false because I want the progress updated on the DOM.
for (var i = 0; i < files.length; i++) {
var fd = new FormData();
fd.append('file', files[i]);
fd.append('galleryid', galleryid);
sendFileToServer(fd); //chain this function call
}
function sendFileToServer(formData)
{
var uploadURL ="includes/ajax/images/uploadImagePage.php"; //Upload URL
var extraData ={}; //Extra Data.
return jqXHR=$.ajax({
xhr: function() {
var xhrobj = $.ajaxSettings.xhr();
if (xhrobj.upload) {
xhrobj.upload.addEventListener('progress', function(event) {
var percent = 0;
var position = event.loaded || event.position;
var total = event.total;
if (event.lengthComputable) {
percent = Math.ceil(position / total * 100);
}
//Set progress
$('#uploadImageResponse').html(percent+'%');
}, false);
}
return xhrobj;
},
url: uploadURL,
type: "POST",
async:true,
contentType:false,
processData: false,
cache: false,
data: formData,
success: function(data){
status.setProgress('Upload completed. 100%.');
}
});
}
I don't understand how jquery deferred objects work.