Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Aborting jQuery().load()

The .load() function of the jQuery library allows you to selectively load elements from another page (subject to certain rules). I would like to know whether it is possible to abort the load process.

In our application, a user can browse a list of items. They may choose to click a button which loads and displays additional information about an item from another document (which can take some time). If they choose a different item in the list whilst a .load() is still happening, I would like the loading to be aborted.

Is this possible? Is it even worth it? Any ideas?

Dan

like image 802
Daniel Situnayake Avatar asked Jun 09 '10 01:06

Daniel Situnayake


3 Answers

You can't do this with .load() directly, since it returns the jQuery object for chaining, but if you change to the full $.ajax() call with .html() you can, like this:

var xhr = $.ajax({
            url: 'mypage.htm',
            success: function(data) {
              $("#myElement").html(data);
            }
          });
//if needed, abort the request later..
xhr.abort();

This uses the .abort() method on the XMLHttpRequest object to abort the load.

like image 70
Nick Craver Avatar answered Oct 21 '22 03:10

Nick Craver


Nick's answer was almost what I needed, but not quite. I was using .load() to load only an image from a page. So, expanding on Nick's answer...

So instead of...

$('#myElement').load('mypage.htm #myImage');

I'm now using...

var xhr = $.ajax({
            url: 'mypage.htm',
            success: function(data) {
              $("#myElement").html($(data).find("#myImage"));
            }
          });
//if needed, abort the request later..
xhr.abort();
like image 8
Homer Avatar answered Oct 21 '22 02:10

Homer


You can do this by using jQuery.ajax manually. It will return a XMLHttpRequest object, which you can call abort on as needed. In the success handler, you can use jQuery.html

like image 1
Matthew Flaschen Avatar answered Oct 21 '22 02:10

Matthew Flaschen