Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting AJAX response body for use in error callback

Tags:

jquery

ajax

jQuery's AJAX error function has the following parameters:

error(XMLHttpRequest, textStatus, errorThrown) 

What's the best cross-browser way to get the response body?

Does this work (reliably in all browsers)?

$.ajax({   error: function(http) {     alert(http.responseText);   } }); 
like image 831
Tom Lehman Avatar asked Jan 18 '10 07:01

Tom Lehman


People also ask

How do you handle errors in Ajax call?

The best way to bubble that error from the server side (using php) to the client side is to send a header through the Ajax request somewhere in the 400's (which is always associated with errors). Once the Ajax request receives this it will trigger your error function.

How do I return a response from Ajax?

The A in Ajax stands for asynchronous. That means sending the request (or rather receiving the response) is taken out of the normal execution flow. In your example, $. ajax returns immediately and the next statement, return result; , is executed before the function you passed as success callback was even called.


Video Answer


1 Answers

As of jQuery 1.4.1 you should use:

var json = JSON.parse(xhr.responseText); 

See http://api.jquery.com/jQuery.parseJSON/.

like image 117
dowski Avatar answered Nov 05 '22 09:11

dowski