Red Red - 4 months ago 9
Ajax Question

How to determine error if using $.post() or $.get()

I would like to know how to handle errors for
$.post or $.get

$.post(URL,data,function(data,status,xhr),dataType)
$.get(URL,data,function(data,status,xhr),dataType)


without using $.ajax which has an error handler.

$.ajax({
url: url,
type: $(this).attr("method"),
dataType: "JSON",
data: data,
processData: false,
contentType: false,
success: function (data, status)
{

},
error: function (xhr, desc, err)
{


}
});

Answer

jQuery's post and get are promisses, so you can chain the functions done, fail and always on these:

var jqxhr = $.post( "example.php", function() {
    alert("success");
})
.done(function() {
    alert("second success");
})
.fail(function() {
    alert("error");
})
.always(function() {
    alert("finished");
});

Or even later, by a varibale:

jqxhr.always(function() {
    alert("second finished");
});

See the documentation.