Reputation: 4342
I'm looking for a JavaScript solution to show some sort of status while an ajax request is taking place. I tried document.getElementById("status").innerHTML = "<h2>Loading....</h2>";
but that didn't work. Any ideas?
function codesDelete(id) {
var ajax;
if (window.XMLHttpRequest) {
ajax = new XMLHttpRequest();
} else {
ajax = new ActiveXObject("Microsoft.XMLHTTP");
}
ajax.onreadystatechange = function() {
if (ajax.readyState === 4 && ajax.status === 200) {
document.getElementById("status").innerHTML = "<h2>Data Deleted!</h2>";
}
}
// this is what i tried
document.getElementById("status").innerHTML = "<h2>Loading....</h2>";
ajax.open("GET", "code.php?id=" + id, true);
ajax.send();
setTimeout(function() {
document.getElementById("status").style.display = "none";
}, 3000);
}
Upvotes: 0
Views: 894
Reputation: 11072
Another method you could do is to use the beforeSend
and complete
callbacks on jQuery.ajax, like so:
$.ajax({
beforeSend:function(){
// Create and insert your loading message here as you desire
// For example, a version of what you were trying to do would be:
$("#status").html("<h2>Loading....</h2>");
},
// ... whatever other things you need, such as a success callback, data, url, etc
complete: function(){
// Remove your loading message here, for example:
$("#status").html("");
}
});
As the names suggest, beforeSend
will be executed before the AJAX call is made. Complete
will execute, regardless whether the AJAX succeeded or failed, after the call is finished.
Upvotes: 1
Reputation: 13775
You can use JQuery's when/done. Start your status indicator and then use when/done like this:
// start the status indicator wherever it's appropriate
StartStatusIndicator();
//Make your ajax call
$.when($.ajax({
type: "POST",
...more stuff...
success: function (json) {
...even more stuff...
}
})).done(function () {
KillYourStatusIndicator();
});
The code inside done
gets fired when the ajax call is finished.
Upvotes: 1