ruby-on-railsajaxinterrupttabbed-view

How to interrupt an AJAX request in rails?


I've the following situation:

A tabbed view sends AJAX requests upon clicking on tabs to change view, each request takes around 3-4 seconds from the time the user clicks on the tab until the view is refreshed (that's healthy and accepted in my case!)

My problem is:

If the user clicked on tab2 while tab1 is loading, the user expects to see the contents of tab2 and ignore the first click on tab1.

What happens is, the contents of tab1 appears first then the contents of tab2. I want to prevent this behavior.

My framework contains of: Ruby 1.8.7 - Rails 2.3.5 - jQuery 1.5.2 (which is use to do AJAX things)

I tried to use some code like that but it didn't work with me

function doRequest(){
  if (lastPageAjaxRequest){
    lastPageAjaxRequest.abort();
    lastPageAjaxRequest = null;
  }

  lastPageAjaxRequest = $.ajax(..);
}

Solution

  • Instead of cancelling the request, just cancel the success callback. You could have a check inside the success callback that looks to see if this is the most recent request, and if so, update the page, otherwise wait for the most recent request to come back.