Below is the code I am using which basically passes multiple files to be uploaded. In the loop each file is resized client side and then uploaded.
I want to execute an ajax call after the loop is finished uploading the photos. The ajax call basically reloads a specific div and refreshes the photos.
How do I prevent the ajax call from executing until the loop has finished.
if (window.File && window.FileReader && window.FileList && window.Blob)
{
var files = document.getElementById('filesToUpload').files;
for(var i = 0; i < files.length; i++)
{
resizeAndUpload(files[i]);
}
// when loop finished, execute ajax call
$.ajax
({
type: "POST",
url: "photos.php",
data: dataString,
success: function(html)
{
$("#photo-body").html(html);
}
});
}
}
function resizeAndUpload(file)
{
var reader = new FileReader();
reader.onloadend = function()
{
var tempImg = new Image();
tempImg.src = reader.result;
tempImg.onload = function()
{
var MAX_WIDTH = 382.25;
var MAX_HEIGHT = 258.5;
var tempW = tempImg.width;
var tempH = tempImg.height;
if (tempW > tempH)
{
if (tempW > MAX_WIDTH)
{
tempH *= MAX_WIDTH / tempW;
tempW = MAX_WIDTH;
}
}
else
{
if (tempH > MAX_HEIGHT)
{
tempW *= MAX_HEIGHT / tempH;
tempH = MAX_HEIGHT;
}
}
var canvas = document.createElement('canvas');
canvas.width = tempW;
canvas.height = tempH;
var ctx = canvas.getContext("2d");
ctx.drawImage(this, 0, 0, tempW, tempH);
var dataURL = canvas.toDataURL("image/jpeg");
var xhr = new XMLHttpRequest();
xhr.onreadystatechange = function(ev)
{
document.getElementById('filesInfo').innerHTML = 'Upload Complete';
};
xhr.open('POST', 'upload-resized-photos.php', true);
xhr.setRequestHeader("Content-type","application/x-www-form-urlencoded");
var data = 'image=' + dataURL;
xhr.send(data);
}
}
reader.readAsDataURL(file);
}
var _validFileExtensions = [".jpg", ".jpeg", ".bmp", ".gif", ".png"];
function Validate(oForm)
{
var arrInputs = oForm.getElementsByTagName("input");
for (var i = 0; i < arrInputs.length; i++)
{
var oInput = arrInputs[i];
if (oInput.type == "file")
{
var sFileName = oInput.value;
if (sFileName.length > 0)
{
var blnValid = false;
for (var j = 0; j < _validFileExtensions.length; j++)
{
var sCurExtension = _validFileExtensions[j];
if (sFileName.substr(sFileName.length - sCurExtension.length, sCurExtension.length).toLowerCase() == sCurExtension.toLowerCase())
{
blnValid = true;
break;
}
}
if (!blnValid)
{
alert("Sorry, " + sFileName + " is invalid, allowed extensions are: " + _validFileExtensions.join(", "));
return false;
}
}
}
}
return true;
}