user1995997
user1995997

Reputation: 591

Jquery ajax post request overlapped with old ones

I am building rss feed reader using php and jquery on wamp server.

On page load, I have list of websites,

<ul class='list'>
     <li>Site1 <input type='hidden' value='http://site1.rss/' /></li>
     <li>Site2 <input type='hidden' value='http://site2.rss/' /></li>
     <li>Site3 <input type='hidden' value='http://site3.rss/' /></li>
</ul>

For fetching feeds from "getFeed.php" page, I use jquery code,

$('.list li').live('click', function() {
     var url = $(this).find('input').val();
     $.post("getFeed.php",
            {url:url},
            function(data) {
                 $('.feed').html(data);
            });
});

This code is working like a charm. Now the problem occur if I click on another site, before first site's request completes.

At that time if first site's response is slow, then I got result from second site as it should. But when first site response late, result changes to first site.

The question is similar to [question]: Abort Ajax requests using jQuery

I already try this code, but not working

$(document).ready(function() {
     var xhr;

     $('.list li').live('click', function() {
          xhr.abort();
          alert("testing flag");
          var url = $(this).find('input').val();
          xhr = $.post("getFeed.php",
                 {url:url},
                 function(data) {
                      $('.feed').html(data);
                 });
     });
})

But, this code fails sending requests. So, I put one testing alert flag after xhr.abort() line. But alert also not working. May be problem in xhr.abort(); line.

Upvotes: 0

Views: 507

Answers (2)

mplungjan
mplungjan

Reputation: 178285

Are you sure you want to abort? I am not even sure it works in all browsers and if it does, the user will likely be surprised that he does not get what he clicked. I would

a) use .on instead of .live which is deprecated and
b) block clicking while the result is fetched or better: queue the clicks

See: What are queues in jQuery?

there is an ajax queue example

Upvotes: 1

Musa
Musa

Reputation: 97707

xhr.abort(); will cause an error since xhr is undefined the first time you call the function, Try something like xhr && xhr.abort();

Upvotes: 1

Related Questions