Handling message request in Ajax HTTP Status Code

0

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

 $.ajax(settings).done(function (response) {
                console.log(response);
                _RecurrentPaymentId = response.Payment.RecurrentPayment.RecurrentPaymentId;
                _NextRecurrency = response.Payment.RecurrentPayment.NextRecurrency;
                _Status = response.Payment.Status;
   });   
    
asked by anonymous 03.12.2018 / 12:48

1 answer

0

You can use the fail function of the request via AJAX, in your case in 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 fail function you can define what you want to do if the request is unsuccessful.

You can also use the statusCode parameter in the AJAX settings, which in case I have no way to know how they are, because you assigned the variable "settings". But you can add the statusCode parameter to a given HTTP return within your settings variable:

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

You can define an action for each HTTP return type.

Official jQuery AJAX documentation: link

    
03.12.2018 / 12:55