jQuery API

.load()

.load( url, [ data ], [ complete(responseText, textStatus, XMLHttpRequest) ] ) Returns: jQuery

Description: Load data from the server and place the returned HTML into the matched element.

  • version added: 1.0.load( url, [ data ], [ complete(responseText, textStatus, XMLHttpRequest) ] )

    urlA string containing the URL to which the request is sent.

    dataA map or string that is sent to the server with the request.

    complete(responseText, textStatus, XMLHttpRequest)A callback function that is executed when the request completes.

This method is the simplest way to fetch data from the server. It is roughly equivalent to $.get(url, data, success) except that it is a method rather than global function and it has an implicit callback function. When a successful response is detected (i.e. when textStatus is "success" or "notmodified"), .load() sets the HTML contents of the matched element to the returned data. This means that most uses of the method can be quite simple:

$('#result').load('ajax/test.html');

The provided callback, if any, is executed after this post-processing has been performed:

$('#result').load('ajax/test.html', function() {
  alert('Load was performed.');
});

In the two examples above, if the current document does not contain an element with an ID of "result," the .load() method is not executed.

The POST method is used if data is provided as an object; otherwise, GET is assumed.

Note: The event handling suite also has a method named .load(). Which one is fired depends on the set of arguments passed.

Loading Page Fragments

The .load() method, unlike $.get(), allows us to specify a portion of the remote document to be inserted. This is achieved with a special syntax for the url parameter. If one or more space characters are included in the string, the portion of the string following the first space is assumed to be a jQuery selector that determines the content to be loaded.

We could modify the example above to use only part of the document that is fetched:

$('#result').load('ajax/test.html #container');

When this method executes, it retrieves the content of ajax/test.html, but then jQuery parses the returned document to find the element with an ID of container. This element, along with its contents, is inserted into the element with an ID of result, and the rest of the retrieved document is discarded.

Note that the document retrieved cannot be a full HTML document; that is, it cannot include (for example) <html>, <title>, or <head> elements. jQuery uses the browser's innerHTML property on a <div> element to parse the document, and most browsers will not allow non-body elements to be parsed in this way.

Examples:

Example: Load the main page's footer navigation into an ordered list.

<!DOCTYPE html>
<html>
<head>
  <style>
 body{ font-size: 12px; font-family: Arial; }
 </style>
  <script src="http://code.jquery.com/jquery-latest.js"></script>
</head>
<body>
	
<b>Footer navigation:</b>
<ol id="new-nav"></ol>

<script>
  $("#new-nav").load("/ #jq-footerNavigation li");
</script>
</body>
</html>

Demo:

Example: Display a notice if the Ajax request encounters an error.

<!DOCTYPE html>
<html>
<head>
  <style>
  body{ font-size: 12px; font-family: Arial; }
  </style>
  <script src="http://code.jquery.com/jquery-latest.js"></script>
</head>
<body>
	
<b>Successful Response (should be blank):</b>
<div id="success"></div>
<b>Error Response:</b>
<div id="error"></div>
  
<script>
$("#success").load("/not-here.php", function(response, status, xhr) {
  if (status == "error") {
    var msg = "Sorry but there was an error: ";
    $("#error").html(msg + xhr.status + " " + xhr.statusText);
  }
});
  </script>
</body>
</html>

Demo:

Example: Load the feeds.html file into the div with the ID of feeds.

$("#feeds").load("feeds.html");

Result:

<div id="feeds"><b>45</b> feeds found.</div>

Example: pass arrays of data to the server.

$("#objectID").load("test.php", { 'choices[]': ["Jon", "Susan"] } );

Example: Same as above, but will POST the additional parameters to the server and a callback that is executed when the server is finished responding.

$("#feeds").load("feeds.php", {limit: 25}, function(){
alert("The last 25 entries in the feed have been loaded");
});

Comments

  • Support requests, bug reports, and off-topic comments will be deleted without warning.

  • Please do post corrections or additional examples for .load() below. We aim to quickly move corrections into the documentation.
  • If you need help, post at the forums or in the #jquery IRC channel.
  • Report bugs on the bug tracker or the jQuery Forum.
  • Discussions about the API specifically should be addressed in the Developing jQuery Core forum.
  • mvc3
    Why is "?_=1270071075752" getting appended to my .load() url??

    URL is "/test/add/1"

    When I echo the request URI in PHP I get the above query string appended to the URL, which is breaking the test I'm trying to run (need this for MVC file extensionless URL a la http:://domain.com/request/action/step)
  • The underscore portion of your query string has to do with caching. $.ajax & $.get have the option to set "cache" to false which appends the "_" portion to your query string.
  • mvc3
    Great, thanks Justin, makes sense now, I am doing just that cache: false; thus the ?_4356576578 GET var.

    As a quick workaround I am doing unset($_GET['_']) on php end, but need to find a better solution as I do need GET at various times for my app.

    Anyway, thanks for the clue-in, lots to learn....
  • Joe
    Just a guess, but that looks like a cache-buster, a way to make sure your request is getting to where it thinks it's going. IE in particular is a bit cache happy with XHRs, and if I recall some vintage versions will actually fail to service requests if you don't make sure to step around the cache. You may be able to step around the cache without it the randomness requesting a POST (which isn't ever supposed to cache in the browser.) One way to determine I'm wrong (but not determine if I'm right) would be to investigate the numbery-bit after the "=" sign. If it changes with every load, it's likely a cache workaround.
  • nicholas_r
    when i load some content using .load() function some scripts which must work with loaded content didn't work. what i doing wrong? thnx
  • Andrew
    .load() works by creating a new element and setting the innerHtml. Script elements in innerHtml usually are either intermittent or just unreliable. Don't do that. Either use, as nobleach suggests below .live(), put your event bindings in the callback, or use jQuery.getScript() to load the scripts that you need.
  • nobleach
    You will need to use live() to bind events to things loaded after the DOM has been updated.

    For example, say you dynamically loaded image thumbnails with load(). Every time you hovered over one of them, you'd want a bigger image somewhere in your page to change. It might look something like this:

    //after load has been called:
    $('.thumbIMG).live('mouseover', function() {
    $('#bigIMG).attr({src: "imageName", alt: "Full Size Pic"});
    })

    obviously I'm leaving out plenty but you get the idea.
  • nicholas_r
    big thnx for help. it was useful))
  • stonebase
    Spent a long time wondering why my load didn't work. Turns out that you can't load to an element with style visibility:hidden (because the element is not receiving events??) but you can load to an element with style display:none.
  • dVyper
    Does this function use remove() to get rid of the elements it is replacing?
    The reason I ask is because I'm wondering whether load() will remove events I have placed on the elements being replaced, or I have to manually unbind events myself when using this function.