chiz
chiz

Reputation: 101

Detecting when ajax success function takes longer than 5 seconds and redirect

Hello I have this script that moves from one page through a href without page load.

It works perfectly, but I want to redirect to the requested page if Ajax takes longer than 5 seconds to respond, usually caused by probably slow internet connection. In this case: Stop the script and load the page normally.

Firstly the href:

<a href="new.php" rel="tab">new</a>
<a href="new1.php" rel="tab">New 1</a>  

This is the script:

<script>
$(function(){ 
  $("a[rel='tab']").click(function(e){
    pageurl = $(this).attr('href'); //get the href clicked
    $.ajax({url:pageurl+'?rel=tab',
      success: function(data){
        $('#mole').html(data); 
      }
    }); 
    if(pageurl!=window.location){
      window.history.pushState({
        path:pageurl
      },'',pageurl);    
    }
    return false;  
  });
});

$(window).bind('popstate', function(){
  $.ajax({
    url:location.pathname+'?rel=tab',
    success: function(data){
      // here how do I detect if the success takes longer than 5 seconds
      // stop the script and load the page normally which is the URL parameter in ajax
      $('#mole').html(data); 
    }
  }); 
}); 
</script>

Upvotes: 0

Views: 444

Answers (1)

sic1
sic1

Reputation: 486

First, we need to add a timeout to the ajax handler so it will cancel the request after 5 seconds (here we use 5000 for milliseconds). Then, based on the docs, head to error and you can see the second param is textStatus. If it was a timeout, this will be equal to "timeout". This is probably your easiest path to what you need to do. Update the error handler as needed for your functionality.

$(window).bind('popstate', function() {
    var url = location.pathname + '?rel=tab';
    $.ajax({
        timeout: 5000,
        url: url,
        success: function(data) {
            $('#mole').html(data);
        },
        error: function(jqXHR, textStatus) {
            if (textStatus === 'timeout') {
                // we know the ajax failed due to a timeout,
                // do what you need here, below is an example.
                window.location = url;
            }
        }
    });
});

Upvotes: 1

Related Questions