views:

187

answers:

3

I want to check if a page returns the status code 401. Is this possible?

Here is my try, but it only returns 0.

$.ajax({
    url: "http://my-ip/test/test.php",
    data: {},
    complete: function(xhr, statusText){
    alert(xhr.status); 
    }
});
+1  A: 

Use the error callback.

For example:

jQuery.ajax({'url': '/this_is_not_found', data: {}, error: function(xhr, status) {
    alert(xhr.status); }
});

Will alert 404

baloo
indeed it did. I'm kinda new to jQuery. But what about 401 status? How do i save the status to a variable? o_O
cvack
Firebug returns this: GET http://my-ip/test/test.php 401 Authorization Required
cvack
It will show 401 the same way.What exactly do you want to do with the error?
baloo
If 401 dont send user to this page. The error only alerts if the page is not found (404)
cvack
Tested this in Firefox where it catched 401 as well, perhaps this is not true for all browsers
baloo
A: 

I think you should also implement the error function of the $.ajax method.

error(XMLHttpRequest, textStatus, errorThrown)Function

A function to be called if the request fails. The function is passed three arguments: The XMLHttpRequest object, a string describing the type of error that occurred and an optional exception object, if one occurred. Possible values for the second argument (besides null) are "timeout", "error", "notmodified" and "parsererror".

$.ajax({
    url: "http://my-ip/test/test.php",
    data: {},
    complete: function(xhr, statusText){
    alert(xhr.status); 
    }
    error: function(xhr, statusText, err){
    alert("Error:" + xhr.status); 
    }
});
GvS
thx, but complete only returns 0. Is it possible to get the 401 code?
cvack
Are you sure complete is called when a HTTP 401 (Unauthorized) is returned from the server? I have not tested, but I would expect that error is called.
GvS
A: 
$.ajax({
    url: "http://my-ip/test/test.php",
    data: {},
    error: function(xhr, statusText, errorThrown){alert(xhr.status);}
});
vartec