Christian Dechery
Christian Dechery

Reputation: 880

Best way to obtain jqXHR status using $.post in jQuery

I found this topic (How to get response status code from jQuery.ajax?) in which it explain how to obtain the return the status, but I'm using $.post which makes it a little different.

I have the following code:

$(function() {
$('#update_marker').submit( function(e) {
e.preventDefault();
$.post($("#update_marker").attr("action"), $("#update_marker").serialize(), function(data) {
    if( $.trim(data).indexOf('<')==0 ) {
        new Messi( lang['dist_general_error'], {title: 'Ops...', titleClass: 'anim error', buttons: [{id: 0, label: 'Fechar', val: 'X'}]});
    } else {
        var json = $.parseJSON( data );
        if( json.status=="success" ) {
            new Messi( json.msg );
        } else {
            new Messi( json.msg, {title: 'Ops..', titleClass: 'anim error', buttons: [{id: 0, label: 'Fechar', val: 'X'}]});
        }
    }
});
return false;
});
});

So I thought I'd change the $.post call to something like

$.post($("#update_marker").attr("action"), $("#update_marker").serialize(), function(data, textStatus, jqXHR) {

and it DOES work if I get jqXHR.status code = 200. But when the status = 500 I get nothing.

I'm trying to achieve this with minimal code changes as I have a lot of functions like this one, and I need to be able to capture the 500 code and treat in all of them.

Any ideas?

Upvotes: 1

Views: 616

Answers (1)

Johanna Larsson
Johanna Larsson

Reputation: 10761

jQuery post only takes success as a parameter. The success handler is only called on successful ajax requests. If the request returns 500, the success handler, your callback, is never executed.

To attach an error handler, you can chain .fail after .post or switch to the broader $.ajax.

The first option means you modify your code by adding .fail like this

$(function() {
  $('#update_marker').submit( function(e) {
    e.preventDefault();
    $.post($("#update_marker").attr("action"), $("#update_marker").serialize(), function(data) {
        if( $.trim(data).indexOf('<')==0 ) {
            new Messi( lang['dist_general_error'], {title: 'Ops...', titleClass: 'anim error', buttons: [{id: 0, label: 'Fechar', val: 'X'}]});
        } else {
            var json = $.parseJSON( data );
            if( json.status=="success" ) {
                new Messi( json.msg );
            } else {
                new Messi( json.msg, {title: 'Ops..', titleClass: 'anim error', buttons: [{id: 0, label: 'Fechar', val: 'X'}]});
            }
        }
    }).fail(function () { console.log("I errored!"); });
    return false;
  });
});

I would recommend getting accustomed to $.ajax though, it is not difficult to get a hang of and it is much more extensible.

Upvotes: 5

Related Questions