Reputation: 342
So I am using Javascript with AJAX to send form data to a PHP file. Once it's done uploading the file to the server, I want a dialogue box to appear to say it's successful, then it reloads. I have that dialogue box done, but it will appear even if there's an error. I though creating a flag would solve this, but it doesn't. I need to wait for the progress to be 100% complete, so I put the code in the progress function. Here's my code:
function uploadImage(){
var done = false;
var xr = new XMLHttpRequest();
xr.upload.addEventListener("progress", progressHandler, false);
xr.addEventListener("error", errorHandler, false);
xr.addEventListener("abort", abortHandler, false);
xr.open("POST", "php/uploadImage.php", true);
xr.onreadystatechange = function(){
if(xr.readyState == 4 && xr.status == 200){
var response = xr.responseText;
if(response=="success"){
done=true;
}else{
_("errorMessage").innerHTML = response;
}
}
}
xr.send(formdata);
function progressHandler(event){
var percent = (event.loaded / event.total) * 100;
_("imageUploadBar").style.width = Math.round(percent) + "%";
if((percent == 100) && (done)){
completeHandler();
}
}
function completeHandler(){
bootbox.dialog({
message: "Image upload is completed.",
title: "Upload Success",
buttons: {
success: {
label: "Continue",
className: "btn btn-success",
callback: function() {
location.reload();
}
}
}
});
}
}
So you can see that if the upload file return success, set done to be true, and if percent is 100, then fire, but this will not fire the completeHandler()
function. Any ideas why or how to get around this?
Upvotes: 0
Views: 334
Reputation: 1352
I believe this will generally fire from onreadystatechange, but adding a 2nd variable should take care of your issue.
var done = false;
var uploaded = false;
var xr = new XMLHttpRequest();
xr.upload.addEventListener("progress", progressHandler, false);
xr.addEventListener("error", errorHandler, false);
xr.addEventListener("abort", abortHandler, false);
xr.open("POST", "php/uploadImage.php", true);
xr.onreadystatechange = function(){
if(xr.readyState == 4 && xr.status == 200){
var response = xr.responseText;
if(response=="success"){
done=true;
if(uploaded && done){
completeHandler();
}
}else{
_("errorMessage").innerHTML = response;
}
}
}
xr.send(formdata);
function progressHandler(event){
var percent = (event.loaded / event.total) * 100;
_("imageUploadBar").style.width = Math.round(percent) + "%";
if(percent == 100) uploaded = true;
if(uploaded && done){
completeHandler();
}
}
function completeHandler(){
bootbox.dialog({
message: "Image upload is completed.",
title: "Upload Success",
buttons: {
success: {
label: "Continue",
className: "btn btn-success",
callback: function() {
location.reload();
}
}
}
});
}
Upvotes: 1