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

Jay Norris
Jay Norris
14,824 Points

no response and .fail()

If there is simply no response from the server, will that trigger the .fail() method? What is the best way to test for nothing being sent?

2 Answers

Erik Nuber
Erik Nuber
20,629 Points

Here is a couple of different ways to test...

function update() {
  $.ajax({
    type: 'GET',
    dataType: 'json',
    url: url,
    timeout: 5000,
    success: function(data, textStatus ){
       alert('request successful');
    },
    error: function(xhr, textStatus, errorThrown){
       alert('request failed');
    }
  });
}

and

$.getJSON('/foo/bar.json')
    .done(function() { alert('request successful'); })
    .fail(function() { alert('request failed'); });

In the first example, there is a timeout of 5 seconds. It isn't necessary to do but, gives a little extra time. You can do anything within the error function including using the information passed back from the fail. That is what is stored in textStatus and errorThrown.

for example.

console.log('ajas request failed. Returned ' + textStatus + ' and it threw an error of ' + errorThrown);

The second way is just using a different method to handle the ajax request but does the same thing.

Jay Norris
Jay Norris
14,824 Points

That is an extremely helpful answer! Thank you.