Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to check if ajax call exists using jQuery?

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?

like image 281
Lucas Avatar asked Oct 26 '12 13:10

Lucas


2 Answers

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().

like image 109
jAndy Avatar answered Sep 17 '22 14:09

jAndy


You can set a callback in your ajax call:

$.ajax({
  url: "foo1.html"
}).done(function() { 
  alert('Done!');
});
like image 36
Trevor Avatar answered Sep 17 '22 14:09

Trevor