Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery $.get or $.post to catch page load error (eg. 404)

Tags:

jquery

post

get

How do you catch Server Error or 404 page not found, when you use $.get or $.post ?

For example:

$.post("/myhandler", { value: 1 }, function(data) {
  alert(data);
});

That will do absolutely nothing if there is a Server Error loading "/myhandler", or if it is not found.

How do you make it notify you if there is an error?

like image 877
Aximili Avatar asked Jan 14 '11 01:01

Aximili


4 Answers

you could do

$.post("/myhandler", { value: 1 }, function(data) {
  alert(data);
}).fail(function(){ 
  // Handle error here
});

fail will be called if theres an error

like image 184
Roberto Arosemena Avatar answered Oct 23 '22 06:10

Roberto Arosemena


use error handler on $.ajax()

$.ajax({
    url: "/myhandler", 
    data: {value: 1},
    type: 'post',
    error: function(XMLHttpRequest, textStatus, errorThrown){
        alert('status:' + XMLHttpRequest.status + ', status text: ' + XMLHttpRequest.statusText);
    },
    success: function(data){}
});

demo

like image 39
Reigel Avatar answered Oct 23 '22 06:10

Reigel


The other answers are nice and all, but there's alternative solutions, namely .ajaxSetup, .ajaxError and other Ajax event handlers (check the ajaxSetup doc page for more info on the rest).

For example, with .ajaxError you can setup a global handler of all your ajax errors from .post, .get, .getJSON and .ajax for a specific set of elements.

$(selector).ajaxError(function(event, xhr, ajaxOptions, errorThrown) {
    // handle ajax error here
});
like image 6
mekwall Avatar answered Oct 23 '22 08:10

mekwall


Use $.ajax instead and use the error callback.

http://api.jquery.com/jQuery.ajax/

like image 2
coreyward Avatar answered Oct 23 '22 08:10

coreyward