Handling request message in Ajax HTTP Status Code

Asked

Viewed 726 times

0

I have a request in Ajax that consults payments on a third party server, I would like to know how to handle HTTP errors. Example: 'server responded with a status of 404 (Not Found)' This error can happen for several reasons, however it only appears in the log, I would like to treat and shows in an elegant way to the user.

 $.ajax(settings).done(function (response) {
                console.log(response);
                _RecurrentPaymentId = response.Payment.RecurrentPayment.RecurrentPaymentId;
                _NextRecurrency = response.Payment.RecurrentPayment.NextRecurrency;
                _Status = response.Payment.Status;
   });   

1 answer

0


You can use the function fail request via AJAX, in your case at jQuery.

It would look something like this:

 $.ajax(settings).done(function (response) {
                console.log(response);
                _RecurrentPaymentId = response.Payment.RecurrentPayment.RecurrentPaymentId;
                _NextRecurrency = response.Payment.RecurrentPayment.NextRecurrency;
                _Status = response.Payment.Status;
}).fail(function() {
    alert( "erro" );
});   

Within the function fail you can define what you want done if the request is unsuccessful.

You can also use the parameter statusCode in the settings of AJAX, in which case I have no way of knowing how they are, because you have assigned the variable "Settings". But you can add the parameter statusCode for a certain HTTP return within its Settings variable:

$.ajax({
  statusCode: {
    404: function() {
      alert("página não encontrada");
    }
  }
});

You can set an action for each type of HTTP return.

Official AJAX documentation at jQuery: http://api.jquery.com/jquery.ajax/

  • Hello @Vinicius Gabriel, thank you for answering. A question in function .fail(function() can I get the status of the error? Example if it is 400, 404 or 500.

  • 1

    @mba yes, the fail() function has 3 callback parameters that you can use any chaos (jqXHR, textStatus, errorThrown). The first object that is returned 'jqXHR' has several properties, including the status of the request. You can query it using jqXHR.status.

  • 1

    @mba an addendum that I don’t know what version of jQuery you are using, but to be able to use this property you need jQuery 1.5 or higher.

  • got it. Thank you very much. Hugs.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.