tags:

views:

19

answers:

3

i noticed that when i provide an invalid URL to get() i get no errors

$.get(nextHref, function(data, status, xhr) {
  alert(status);
  if (status == "error") {
    alert("an error has occured: " + xhr.status + " " + xhr.statusText);
  }

alert(status); nv even runs when i provide an invalid URL

+3  A: 

From the API page:

If a request with jQuery.get() returns an error code, it will fail silently unless the script has also called the global .ajaxError() method.

Read about the ajaxError here.

Basically what you need to do is to attach ajaxError to some item, and handle the error from there:

We can attach our event handler to any element:

$('.log').ajaxError(function() {
  $(this).text('Triggered ajaxError handler.');
});

Now, we can make an Ajax request using any jQuery method:

$('.trigger').click(function() {
  $('.result').load('ajax/missing.html');
});
peirix
+3  A: 

The $.get() callback is a success function, so this will never run on error, you can either use $.ajax() for the full version, or rig up a global error event handler, whichever is more appropriate.

If you want to use $.ajax(), use the error callback, like this:

$.ajax({
  url: nextHref,
  success: function(data) {
    //do something with good data, what comes after your if statement currently
  },
  error: function(xhr, status, error) {
    alert("an error has occured: " + xhr.status + " " + xhr.statusText);
  }
});

Or use the global event handler $().ajaxError() like this:

$(document).ajaxError(function(e, xhr) {
    alert("an error has occured: " + xhr.status + " " + xhr.statusText);   
});

Or, use $.ajaxSetup() to add an error handler for all requests, like this:

$.ajaxSetup({
  error: function(xhr, status, error) {
    alert("an error has occured: " + xhr.status + " " + xhr.statusText);
  }
});
Nick Craver
A: 

if you wish to catch the error use this :

$.ajax({
   url : url,
   success : function(result) {
      //doSomething
   },
   error : function(request, status, error) {
       if(status == 'parsererror' || status == 'error') {
         //doSomething
       }
   }
});
Puaka