how to set a maximum response time in ajax?

1

I have a call through ajax that returns me an answer, what I want to do is, for example there are times when the answer takes a long time and in these cases I would like to put a message that says something like that your request took longer than allowed, for example that this message appears after 20 seconds

I pass my code of the request thank you:

function generarnombre(){


      $("#cargando").css("display", "inline");

     $.ajax({
       type : "POST",
       url : "reniec.php",
       data : $("#fromulariof1").serialize(),
       success : function(data){
                 $("#resultado_reniec").html(data);
                     $("#cargando").css("display", "none");

       }  

      })

      return false;

}
    
asked by ingswsm 19.09.2017 в 13:12
source

2 answers

2

Easy, you can use the timeout method to set a maximum response time. Something like that:

function generarnombre(){


  $("#cargando").css("display", "inline");

 $.ajax({
   type : "POST",
   url : "reniec.php",
   data : $("#fromulariof1").serialize(),
   success : function(data){
             $("#resultado_reniec").html(data);
                 $("#cargando").css("display", "none");

   },
   timeout: 20000, // sets timeout to 20 seconds  
   error: function(request, status, err) {
        if (status == "timeout") {
            alert("Su petición demoro mas de lo permitido");
        } else {
            // another error occured  
            alert("error: " + request + status + err);
        }
    }
  })

  return false;

}
    
answered by 19.09.2017 в 13:17
2

You can set the value of the timeout property (in milliseconds) in the ajax request.

If it reaches the set time, the error function will be executed and in the property statusText will have a value timeout :

function generarnombre(){


      $("#cargando").css("display", "inline");

     $.ajax({
       type : "POST",
       url : "reniec.php",
       data : $("#fromulariof1").serialize(),
       success : function(data){
                 $("#resultado_reniec").html(data);
                     $("#cargando").css("display", "none");

       },
       error: function(e){
        if (e.statusText==='timeout'){
          console.log('Tiempo de espera agotado');
        }
        else{
          console.log(e.statusText);
        }
       },
       timeout: 20000
      });

      return false;

}

$(function(){
  generarnombre();
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="cargando"></div>
    
answered by 19.09.2017 в 13:21