Reputation: 21
I am making an ajax request which actually looks like this.
$loading = $("#loadingDiv")
function loadBuildList() {
$.ajax({
async:true,
url:"ajax_test.php",
beforeSend : function() { $loading.show(); },
success : function() { $loading.hide() }
});
}
Now, I need to display a spinner image while the ajax is running, Also my code is not supposed to execute further until the ajax's execution is over. If I make async:false
I will not be able to load the spinner. If I make async:true
I will not be able to wait till ajax execution is over.
Below is how I am calling the function loadBuildList
...
//$loading.show(); // this I will use when aync : false
loadBuildList()
//$loading.hide();
...
How can I handle such situation? Can anybody please help me with this?
Upvotes: 1
Views: 97
Reputation: 28611
Handling the spinner is fine with .complete
(so picks up both success and error):
function loadBuildList() {
var loading = $("#loadingDiv")
loading.show();
$.ajax({
url:"ajax_test.php",
complete : function() { loading.hide() }
});
}
However, this comment is more interesting:
my code is not supposed to execute further
It's not that you don't want to execute further, it's that you want to continue execution when the ajax call has completed.
You can do this by returning the $.ajax object, which is a promise
. With the promise, you can then add chain calls in your own code. This is similar to using a callback parameter, but generally more flexible:
function loadBuildList() {
return $.ajax({
...
}
// calling code
loadBuildList().done(function() {
// code to run when the list has loaded
});
Upvotes: 1
Reputation: 5989
On the basis of code snippet you have provided it seems there is no need to use beforeSend
as you just have one call on the page. You can do it following way.
$loading = $("#loadingDiv");
function loadBuildList() {
$loading.show(); // Show spinner before AJAX call
$.ajax({
async:true,
url:"ajax_test.php",
// beforeSend : function() { },
success : function() { $loading.hide() }
});
}
You can still try to make it as mentioned by @zurfyx but usually this practice is followed when you need something centralized and not for individual AJAX calls.
Upvotes: 1
Reputation: 32767
You should never use async:false
, or you'll stop the whole execution thread until it has got a response.
Everything that needs to be run after an async execution, in this case $.ajax
needs to be written inside the callback. That is inside success for JQuery $.ajax
.
$loading = $("#loadingDiv")
function loadBuildList() {
$.ajax({
async:true,
url:"ajax_test.php",
beforeSend : function() { $loading.show(); },
success : function() {
$loading.hide();
// Stuff after $.ajax goes here.
},
fail: function() {
// Or here.
}
});
}
You should also have a read at How do I return the response from an asynchronous call?
Upvotes: 1