views:

103

answers:

3

Hi, i do 2 different ajax request via jQuery and i have to check the other one is active or not. How can i do that ?

one of example from my ajax requests:

active_project_categories_ajax = $.ajax(
{
    url: "/ajax/get_skill_list",
    dataType: 'json',
    ......
});

i need something like that: active_project_categories_ajax.status()

+1  A: 

You'd do that by subscribing to AJAX events and updating a status indicator:

var status;

$.ajax({
   beforeSend: function(){
     status = 1;
   },
   complete: function(){
     status = 2;
   }
   // ...
});
deceze
+1  A: 

You're almost there, status is a property of XMLHttpRequest, and not a function. jQuery.ajax returns an object of XMLHttpRequest. Hold on to this as you're already doing:

var req = $.ajax(..);

Then call status on that object when needed, not status()

req.status
Anurag
+1  A: 

since you are getting back the XMLHttpRequest object, you can always look at

active_project_categories_ajax.readyState
active_project_categories_ajax.status

the readyState needs to be 4 for it to be completed (success or error). so if it is less than 4, then it is still active.

this is the readyState:

// states
  const unsigned short UNSENT = 0;
  const unsigned short OPENED = 1;
  const unsigned short HEADERS_RECEIVED = 2;
  const unsigned short LOADING = 3;
  const unsigned short DONE = 4;

quoted from: http://www.w3.org/TR/XMLHttpRequest/#the-xmlhttprequest-interface

You cannot look at the status before readyState becomes 4. otherwise there may be an exception raised. (actually, i wrote a php file that return 1MB of data... and when the readyState was 3, the status was also 200. i suspect the status would be 200 if the readyState stopped at 2 as well).

動靜能量
what kind of exception?
Anurag
this is what I got from the Firebug console: uncaught exception: [Exception... "Component returned failure code: 0x80040111 (NS_ERROR_NOT_AVAILABLE) [nsIXMLHttpRequest.status]" nsresult: "0x80040111 (NS_ERROR_NOT_AVAILABLE)" location: "JS frame :: http://www.somewebsite.com/proj/js/ajax_status/ :: anonymous :: line 54" data: no]
動靜能量