I'm trying to write a jQuery function to let users upload many files at once. Here's the function I thought to give the user some feedback about the upload process progress.
function uploadFiles(numbersOfFiles, start) {
$("#info").html(start + " files uploaded");
$.post('upload.php', {
start: start
}, function (data) {
start += 5;
if (start < numbersOfFiles) {
uploadFiles(numbersOfFiles, start);
} else {
$("#info").html("All files have been uploaded");
}
});
}
The function calls a php script to upload 5 files, then if there are more files to upload it calls the script again. The whole process works. I've tried it with 100 files. The only thing that doesn't work is the #info div updating. The div get updated the first time and then again only to show "All files have been uploaded". So there's no feedback for the user about the uploading process. I can't understand why... Any help?
$.post
is executed asynchronously. Meaning jQuery does not wait for the POST to finish before executing another $.post
Hence jQuery will very quickly execute all the POSTs and all you got to see is "All files have been uploaded" message, even though the actual POST is still waiting for responds in the background.
To do what you want to do, recursively call uploadFiles
in complete:
.