Ali
Ali

Reputation: 267049

How to create an error callback when a Jquery AJAX request fails?

I'm making ajax requests using the following format:

$post('url', {someData:true}, myCallbackFunction, 'json);

The problem is, if on the server side any status code other than 200 is returned, the callback function is never called.

For example, if the user's session has timed out, I want to return 401 (unauthorized) as the status code, alongwith a JSON object as result which has an error message. But, unless the status code is 200, the callback function doesn't get called.

Any ideas how to work around this?

Upvotes: 0

Views: 108

Answers (1)

Jithesh
Jithesh

Reputation: 972

function errorCallback(response){
    alert(response.status + ' ' + response.statusText );
}
$.post('url', {someData:true}, myCallbackFunction, 'json').fail(errorCallback);

See jquery.post for more details.

Upvotes: 3

Related Questions