how to handle errors using $ .ajax ()?

0

I have tried everything and I can not catch the errors like for example when there is no internet connection or when you can not make the request with the server, I hope you understand me and can help me, I have said that you can handle the errors in the success, but I still do not know how to do it, I leave you the code.

$.ajax({
        data:  parameters,
        url:   'createClient.php',
        type:  'post',

// It runs during the sending of the request

        beforeSend:function(response){ 
        $('#cargando').css({display:'block'});
        $('#exito').html('Procesando...');
        },

        //Se ejecuta cuando termino la petición
        complete:function(response){
            $('#exito').html('Exito...');
        },

        // se ejecuta al termino de la petición y está fue correcta
        success: function (response) {
            console.log(response);
            //Cargamos finalmente el contenido deseado
            location.href ="reparacion-iphone-cdmx-gracias.php";

        },
         error: function (response) {
            alert(error con la petición);
        }
    });
    
asked by Rodrigo0 11.06.2017 в 19:37
source

2 answers

2

Unfortunately $.ajax() can not capture errors like no hay conexión a internet , that process you should do before executing the AJAX.

if(navigator.onLine){
  console.info('Conectado a internet');
  $.ajax(...);
} else {
  console.info('Sin conexión a internet');
}

The error function will only detect if something went wrong making the request with the server .

As for "handling errors in success", it means that your server has to return some error code (in case something has gone wrong in the backend), this error code will be interpreted by your Javascript .

    
answered by 11.06.2017 в 19:57
0

I'm new to stackoverflow.

I share a simple way to capture an error.

         function cargarsubmenus() {
         $.get(
          '@Url.Action("Lista_menus")?menu='+ valormenu
          )
         .done(function (result2) {
          //si la acción se ejecuta correctamente se hará lo siguiente
          $.each(result2, function (i, row) {
              var $option = $('<label>');
              $option.val(row.Indice);
              $option.html(row.NombreMenu);
              $('#contenido').append($option);
              })
           })
          .fail(function (result2) {
          //en caso de fallo por algún motivo.
          console.log('Error al obtener los datos');
          }
         );
        };

I think the best way to capture errors is through an SP, since you will manage every type of error that could present you.

I hope it helps, greetings.

    
answered by 02.01.2018 в 18:11