Search code examples
jqueryajaxhistorypushstateabort

jquery abort all previous ajax requests


I tried to abort all the previous ajax request made to load a page. However I have some difficulties to make it work.

I use jquery ajaxify to ajaxify my website (https://github.com/browserstate/ajaxify). But this script didn't abort previous ajax requests. If I quickly load several page I can see all the previous page content appended then re-appended....And sometimes the appended data are not the last...

Here the script :

(function(window,undefined){

    $(function(){

        var xhr = null;

        $.fn.ajaxify = function(){
                // Prepare
            var $this = $(this);
                // Ajaxify
            $this.find('a').click(function(event){
                // Prepare
                var $this = $(this),
                    url = $this.attr('href'),
                    title = $this.attr('title')||null;

                History.pushState(null,title,url);
                event.preventDefault();
                return false;
            });
            return $this;
        }

        $body.ajaxify();

        $window.bind('statechange',function(){
                // Prepare Variables
            var State = History.getState(),
                url = State.url,
                relativeUrl = url.replace(rootUrl,'');

            if (xhr) {
                xhr.abort();
            }

            xhr = $.ajax({
                url: url,
                beforeSend: function() {},
                success: function(data) {/*append data*/},
                error: function(jqXHR, textStatus, errorThrown){
                    document.location.href = url;
                    return false;
                }
            });

        });

    });


})(window);

Edit: When I abort, the entire site reload the page without ajax. I need to only load the last link click and abort all previous necessaries ajax requests in order to preserve ajax functionnality.

How can I abort this statechange?


Solution

  • The issue is that when we do Abort on Ajax... it triggers the error with textStatus=abort. In your case you are changing location.href hence causing a reload. You can verify it by alert or console.log the textStatus

    Solution: In your error handler make sure the textStatus is not abort.

     xhr = $.ajax({
             url: url,
             beforeSend: function() {},
             success: function(data) {/*append data*/},
             error: function(jqXHR, textStatus, errorThrown){
                // aborting actually triggers error with textstatus=abort            
                if (textStatus != "abort") { 
                   document.location.href = url;
                   return false;
                }
             }
      });