Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

JavaScript AJAX Basics (retiring) jQuery and AJAX Handling Errors

Giuseppe Ardito
Giuseppe Ardito
14,130 Points

When .fail() method cannot be applied...

Hi all!

I would like to better understand how to check the status of the request in the "success" callback, in case the .fail() cannot be applied in the examples mentioned in the last part of this video. (we are using load method, sending a cross-domain request with PJSON, etc.)

Do you we need, basically, to check the jqXHR.status and use an IF condition?

1 Answer

Nicolás Carrasco-Stevenson
PLUS
Nicolás Carrasco-Stevenson
Courses Plus Student 5,668 Points

In the jQuery API Documentation about .load() there is a really good example on how to handle errors:

$( "#success" ).load( "/not-here.php", function( response, status, xhr ) {
  if ( status == "error" ) {
    var msg = "Sorry but there was an error: ";
    $( "#error" ).html( msg + xhr.status + " " + xhr.statusText );
  }
});

The relevant part here is that you can pass the status of the request as an argument to the callback function that is in turn passed to the load() method. Later you can use an 'if' block to test if the status is an error or a success.

Giuseppe Ardito
Giuseppe Ardito
14,130 Points

Great stuff, thank you! Exactly what I was looking for!