Reputation: 17343
I know my title isn't very clear.
For example, this is the structure of my code:
if (foo == something) {
// Ajax call 1, let it be $.ajax("foo1.html") and so on
} else {
// Ajax call 2, let it be $.ajax("foo2.html") and so on
}
How would I test if $.ajax("foo1.html")
has actually been run?
Please don't tell me to test if foo == something
again. My actual code is much, much more complicated, so please answer the question from the view of the ajax call.
Is this possible at all?
Upvotes: 5
Views: 12803
Reputation: 952
I had similar issues. I used this code:
var isRunning = false; // whether ajax call is running
if(isRunning==false){
isRunning = true;
$.ajax({
// do your stuff
// make sure you set
isRunning = false;
// on success
});
}
Upvotes: 1
Reputation: 3635
Wrap the call in a try catch.
if the call to 'foo1' fails because the method does not exist on the server, in the catch call foo two and then three all the way down until you have exhausted all your fall backs.
If you know the method exists and think it will fail, then set a status on it that can be returned if the server fails then handle the return in the ajax callback.
Upvotes: 0
Reputation: 14025
I would set variable before AJAX call and reset it in the success callback like that :
var isRunning = true;
$.ajax({
url: url,
success: function(resp){
isRunning = false;
}
});
Upvotes: 5
Reputation: 236202
I'm not sure if I understood you right, but jQuery will mix a Deferred object into its jXHR object and you can just check its state.
var resp = $.ajax({});
// somewhere else...
if( resp.state() === 'resolved' ) {
}
Other states are rejected
and pending
, see http://api.jquery.com/deferred.state/
Of course, you can get all advantages of those Deferred objects aswell, like adding more event handlers for certain things afterwards (.done()
, .fail()
, etc) or just wait for the promise to fullfil using $.when()
.
Upvotes: 13
Reputation: 6689
You can set a callback in your ajax call:
$.ajax({
url: "foo1.html"
}).done(function() {
alert('Done!');
});
Upvotes: 6