3

There I had a problem with ajax pagination with HTML API Pushstate.

So, this is my code:

<ul class="small">
    <li>
        <p>a</p>
    </li>
</ul>

<ul class="paging">
    <li><a href=/page2>2</a></li>
    <li><a href=/page3>3</a><li>
    <li><a href=/page4>4</a><li>
</ul>


$(document).ready(function() {
    if (window.history && history.pushState) {
        historyedited = false;
        $(window).on('popstate', function(e) {
            if (historyedited) {
                loadProducts(location.pathname + location.search);
            }
        });
        doPager();
    }
});

function doPager() {
    $('.paging li a').click(function(e) {
        e.preventDefault();
        loadProducts($(this).attr('href'));
        history.pushState(null, null, $(this).attr('href'));
        historyedited = true;
    });
}

function loadProducts(url) {
    $('.small li').empty().load(url + ' .small', function() {
        doPager();
    });
}

It is working good at first click, but when I click 2, or 3, or 4 times the problem cames up. It makes multiple Ajax request and things are getting worser. What is wrong with my code?

Alexandr Lazarev
  • 12,554
  • 4
  • 38
  • 47
Ching Ching
  • 217
  • 1
  • 5
  • 15
  • 1
    Isn't it normal you make multiple ajax calls when the point of your click is making an ajax call? – Naruto Sep 15 '15 at 10:26
  • possible duplicate of [How many concurrent AJAX (XmlHttpRequest) requests are allowed in popular browsers?](http://stackoverflow.com/questions/561046/how-many-concurrent-ajax-xmlhttprequest-requests-are-allowed-in-popular-browse) – Halayem Anis Sep 15 '15 at 10:37

2 Answers2

0

When clicking on a new page you'll have to cancel the previous request first. You can't use .load() for this, so better use $.ajax instead. You could do it like this:

$(document).ready(function() {
    $('.paging li a').click(function(e) {
        e.preventDefault();

        // Cancel previous request if there is one
        if(typeof xhr !== 'undefined') {
            xhr.abort();
        }

        // Do the new request
        var xhr = $.ajax({
            url: $(this).attr('href') + '.small',
            success: function(data) {
                 $('.small li').html(data);
                 doPager();
            }
        });
    });
});
Evdv
  • 75
  • 1
  • 8
0

Try the folowing method

$(document).ready(function() {
if (window.history && history.pushState) {
    historyedited = false;$(window).on('popstate', function(e) {
        if (historyedited) {
            loadProducts(location.pathname + location.search);
        }
    });
}
$('.paging li a').click(function(e) {
    e.preventDefault();
    loadProducts($(this).attr('href'));
    history.pushState(null, null, $(this).attr('href'));
    historyedited = true;
});});


function loadProducts(url){
$('.small li').empty().load(url + ' .small');}
Arul James
  • 127
  • 1
  • 12