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.

Note: The event handling suite also has a method named .load(). jQuery determines which method to fire based on the set of arguments passed to it.

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');

Callback Function

If a "complete" callback is provided, it is executed after post-processing and HTML insertion has been performed. The callback is fired once for each element in the jQuery collection, and this is set to each DOM element in turn.

$('#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.

Request Method

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

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.

jQuery uses the browser's .innerHTML property to parse the retrieved document and insert it into the current document. During this process, browsers often filter elements from the document such as <html>, <title>, or <head> elements. As a result, the elements retrieved by .load() may not be exactly the same as if the document were retrieved directly by the browser.

Script Execution

When calling .load() using a URL without a suffixed selector expression, the content is passed to .html() prior to scripts being removed. This executes the script blocks before they are discarded. If .load() is called with a selector expression appended to the URL, however, the scripts are stripped out prior to the DOM being updated, and thus are not executed. An example of both cases can be seen below:

Here, any JavaScript loaded into #a as a part of the document will successfully execute.

$('#a').load('article.html');

However, in the following case, script blocks in the document being loaded into #b are stripped out and not executed:

$('#b').load('article.html #target');

Additional Notes:

  • Due to browser security restrictions, most "Ajax" requests are subject to the same origin policy; the request can not successfully retrieve data from a different domain, subdomain, or protocol.

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");
});

Support and Contributions

Need help with .load() or have a question about it? Visit the jQuery Forum or the #jquery channel on irc.freenode.net.

Think you've discovered a jQuery bug related to .load()? Report it to the jQuery core team.

Found a problem with this documentation? Report it on the GitHub issue tracker

  • Uwe A.

    i have a bunch pages that i want to load into divs in a single page, they are full html pages, but i want only the content inside of body of it, headers have scripts and so does the body, i tried $(“#divID”).load('filename.html body *') no avail! how shall i do it?

  • B Hulsman

    I have a content div on my page and now i get:

    $(“#content”).load(“page.html #content”);

    This way I have 2x the div with id “content” in my DOM. Is there a way to load the contents of #content instead of the div itself?

    • http://www.learningjquery.com/ Karl Swedberg

      If all the text in #content is within child elements, you could do this:

      $("#content").load("page.html #content > *");

  • User

    Hi, I wish to load aspx in my PHP page, but it is only working in IE, not chrome/Firefox. Below is my coding:

    $(“.Category_1″).live(“click”, function(){
    var Report_Selected = ($(this).attr('id')); //id is the URL
    $('#result').load(Report_Selected);
    });

  • jerallyn

    If load(); is called on rollover, is there a way you can cancel the load(); on rollout of the element?

  • Designer

    Trying to run this $(document).ready(function(e) {
    var loadUrl=”includes/showreports.php”;
    var sdate = $(“#sdate”).val();
    var edate = $(“#edate”).val();

    $(“#submitrep”).click(function(){
    $(“#results”).load(loadUrl,'sdate=+sdate+&edate=+edate+');
    });

    });

    • Designer

      how do i pass the variables properly…

    • Andrew

      if you want to do a GET request, just add those parameters to the loadURL.

      var loadUrl=”includes/showreports.php?sdate=”+$(“#sdate”).val()+”&edate=”+$(“#edate”).val();

  • Maykel Llanes

    I want use .load(); in an aplication develop with Django framework , i use Jquery for presentation layer.
    My problem is:
    i am trying this:
    1- .load(“D:Job-Thingsworkspacesipatxreport_appusptoindex.html”);
    2- .load(“file:///D:/Job-Things/workspace/sipatx/report_app/uspto/index.html”);
    but does not work, Im really need an answer, help me please.

    • Andrew

      you can't do that because it's a huge security risk. if browsers let you do that, you could steal files from people's computers without them knowing.

    • Bieyinan

      mayber the URL path must be reletaive path

  • Jemmyeee

    how can spring3 mvc recive the json data post by jquery load()? it seams to can revive! anyone help me?

  • Jemmyeee

    how can spring3 mvc recive the json data post by jquery load()? it seams to can revive! anyone help me?

  • Sudhakarreddy

    why .load() function not working with google chrome browser???? reply me as soon as possible

    • http://jestrade.tumblr.com Jes

      it works with Chrome correctly

  • Kalpana

    .load() working with mozilla but not with google chrome why????

  • Kostya1215

    I'm trying to use .load to load html page that has a javascript inside which is parsing and displaying xml file and it's not working.
    i'm loading it like this: $('#NewPage').load('/abc/path/new.html #main_page');
    But it's not loading the script, any ideas?

  • Chris Moore

    If you want to load some content into a div and then manipulate it afterwards ((ie: loading something your use a template for a message window and then want to change the message contents) you *must* do it by wrapping it in the completed function handler..

    Don't just throw it a few lines down, you'll get random chances that the selector will fail..

  • Icecappacino

    I'm trying to get the innerHTML of a “tag” using:

    $('#msg').load('includes/ text',{action: 'gettweets'}, function(data,s,t){ alert(s); alert(t); alert(data); });

    works in all browsers except IE 7

    …I can't modify the source data.

  • JqueryNewbie

    How would you do this if the page you want fragments from doesn't have id attributes in the tags and you can't add ids?

    • http://www.learningjquery.com/ Karl Swedberg

      You don't have to use an ID selector. See http://api.jquery.com/category…/ for more information.

      • Mike

        In my testing it appears to only work when fed to an ID selector.

        • Mike

          Just kidding. I do run into a problem though when trying $('.some_class')[0].load('someurl');

          • Kurt

            Your selector needs to incorporate ':first' (or similar), instead of using [0]. Once you use [0], you no longer have a jQuery object, but instead a DOM element, which doesn't have a 'load()' method.

  • Ryan

    Is there any way I can use the .load event with a dynamic image such as this
    http://www.seewhosoutthere.com…

    Whenever I try to use the load method to reload that page into the document it just come out as ��������

  • J. Bosch

    When I do:
    $('#content_container').load('page.php #content', { action: 'modify' });

    The javascript from #content is not loaded at all? So I need to refresh my whole page before it's loaded again.
    I have the javascript between <script type=”text/javascript”> and </script>

    • E. Hymel

      I've noticed the same thing. Very inconvenient!!

    • ryan

      I face similar case too, but I'm using JSP.
      Does load() actually cause the jsp page to be sent to the web server before loading at client side ?

    • ryan

      I solved that issue. By using:
      $.ajaxSetup ({
      // Disable caching of AJAX responses
      cache: false
      });

      I suppose the reason why my page doesnt reload is due to caching. Hope this would solve your problem too.

      • J. Bosch

        We don't use caching on php files, only on static ones.
        It's not that the page doesn't refresh, it removes everything between <script> tags from the file that is loaded with load().
        I noticed it only removes everything between <script> tags when you use a selector. When I don't use a selector it is still inside the file that is loaded with load().
        I'm now forced to do a page reload, otherwise the website has a lack of functionality..</script>

      • ManOVision

        Thanks…worked perfectly to disable the cache.

  • http://twitter.com/KamilKlosowski Kamil Kłosowski

    i use code: $(“#content”).load(location.href+” #content>*”,”");

    it's all ok – but as i look at page request headers – it downloads style.css, and few js files i've got on page. how i can avoid that? request size is like 100kb. is it necessary? any option there?

    thanks in advice

  • http://twitter.com/KamilKlosowski Kamil Kłosowski

    i use code: $(“#content”).load(location.href+” #content>*”,”");

    it's all ok – but as i look at page request headers – it downloads style.css, and few js files i've got on page. how i can avoid that? request size is like 100kb. is it necessary? any option there?

    thanks in advice

  • Learnfromforum

    I can load a page (e.g. aaa.html) into a <div> of index.html. But when I click on a href-link (e.g. bbb.html) on page aaa.html, the bbb.html is not loaded in the <div> anymore. How can I open all pages from href-links in aaa.html into <div> of index.html?</div></div></div>

  • Tyuk

    Hi!
    I've got a problem. This is my source:
    function ajaxol (){
    $.ajaxSetup({cache:false})
    $('#ebbe').load('ajax.php');
    }
    It works with IE and Firefox, but it doesn't work with Chrome. I have almost everything tried and I have no idea what to do:( Any idea?

  • Guest2010_12

    i can't load html page from other website using .load(),
    code exemple :
    $(“#test”).load(“http://www.domainname.com/inde…“);
    thanks

    • Skeggy11

      This is due to XSS. You will need to use JSONP or a Web Service.

      • Lopes80andre

        There are examples on how to do this?

        Best Regards.

  • Kenny

    When trying this , i noticed that JQuery moves my scripts to the head , executes them , and then removes them.

    While this is a great feature , is there any way to tweak this behaviour ?
    The main problem is that it's hard to debug the scripts in this way , because it's already removed.

  • Sumairz

    .load() is not running at my pc at all

    it is not returning anything

  • Jerinaw

    I'm guess you can't use .load() with xslts? Meaning load some xml and apply and xsl to it?
    Also, what will happen if the contents of the element that the new content is being loaded into has event handlers attached?

  • http://twitter.com/n1tr0b n1tr0b

    For some reason, It can't load iFrames.

    I'm trying to output reCaptcha, it will return as an iFrame but never outputs it to the browser.

  • Rushin Sukhadiya

    thanx its working it solved my problem with XmlHttp

  • Rushin Sukhadiya

    But not working in IE what to do plz help…

  • Rushin Sukhadiya

    thanx its working it solved my problem with XmlHttp

  • Rushin Sukhadiya

    But not working in IE what to do plz help…

  • Jo

    this works well, thanks!

  • Bob

    I'm trying to load a JavaDoc HTML file via the load() function, but when it loads the file, Javascript (document.writeln(….)) within the JavaDoc executes, which causes the current window to be overwritten.
    Is there any way to tell this function to NOT load <script> tag contents from the target file?
    Thanks!</script>

  • sbhor

    Hey guys I am kinda new to jquery and working on a simple page loader script that would fetch content from the server and append it one after the other vertically on a page… just wondering if anyone has done this before and if so are ther any examples that are out there which can help me achieve the same… thank you guys in advance for everything…

  • http://twitter.com/styledev styledev

    The fact that the script code is being removed when you target a selector is really annoying. I am trying to use AJAX so I do not need to reload the page!

  • Kelvne

    It isn't working on chrome, This code isn't working, ONLY ON GOOGLE CHROME:

    $(document).ready(function(){
    $(“#main”).load('main.php')
    }

    • Richard

      My guess is, having not tested this out myself, that Chrome requires each JavaScript line to end with a semi-colon, which the line in the function doesn't. You also need a closing bracked and semi-colon at the very end, after the curly brace.

  • Phant0m

    Hello everybody,
    is it posible to display some kind of an animated busy-image until the data is loaded?

    • Senkal86

      Yes it is realy simple.
      One way is to put some aniamted gif (loader) in to container, before ajax request. After ajax request just remove it.

  • ds

    is it possible to use the .load function on a standard wordpress URL?
    i want to load a wordpress page that has an URL like “http://www.example.com/?page_id=223

    i can not change the wordpress permalink structure, because that would mess up my entire website.

    thanks in advance!

    • http://www.ldexterldesign.co.uk/ ldexterldesign

      I'm trying to throw the function a baseURL right now, because I want to make the script portable. I've been told a PHP proxy or JSONP has the answer for cross-site scripting (although this isn't really a security thing)…

      Drop a reply in [here] if you find a documented answer.

      Cheers,

    • ac

      search themes for jquery plugin support…many offer this now.

  • Anton-ny

    Страница некорректно загружается из-за неправильного закрытия тэгов
    Например “/>” вместо “>”

    Page loaded incorrectly due to improper closing tags
    For example “/>” instead of “>”

    • Vasya

      на чем смотрели?

  • Test

    dgfdgfg

  • Roodlokje

    How can I apply the css to the external html?
    Thanks for helping

    • Andrei Rafai

      by assigning a class to the the external html that you want to load….a css class defined in the css of the main class, the one which will contain the exeternal html

  • http://pulse.yahoo.com/_VXYINHAQSHSQFVEGCP72476TZM Danielle Girlberta

    how do can i load xml document and display it?

  • Lucky

    $(“#feeds”).load(“feeds.php”, {limit: 25}, function(){
    alert(“The last 25 entries in the feed have been loaded”);
    }); will this be helpfull for me to load 25rows at a time on scroll.. ie incremental load.. please help me on this…

  • http://nicholas-boll.myopenid.com/ Nicholas Boll

    If you are using PHP, you can use curl:

    http://blog.unitedheroes.net/curl/

    You can set up a generic php page like ‘curl_url.php’ and send ‘url’ as a parameter for your php file to curl. And it would just have to echo out the buffer returned by curl_exec(). This might pose a security risk, however, so tread carefully.

  • Filipe

    Too bad it didn't work.
    And even if it worked fine, it wouldn't be the solution I'm looking for (at least for my single problem). If I have to rewrite the whole js code in the current page it would bust all the dynamism. I mean, the idea of loading pages into modals, for example, is to work like includes. I don't have to worry about updating more than a single file. Just the original one.
    But I appreciate your effort on trying to help us.

    Is there anyone who still holds hope for this issue? Thanks

  • Filipe

    Finally I found a solution. Look up @ my response in the first post.

  • http://www.JenniferSuarez.com Jennifer Suarez

    Filipe,
    What did you use for a solution? I'm not sure what you mean by “look up at my response in the first post.” The only things I see are your questions but not an answer.

    Thx!

  • Lee

    Remember this is still javascript. You have to concat your var to your string.

    $('#container').load(pageURL + ' #container');

  • http://twitter.com/WraithKenny Kenneth Newman

    You'll want to do some .wrap() and .unwrap(), else you'll have double '#container's

    var pageURL=$(this).attr('href');
    $('#container').wrap(“<div id=”ajaxLoading”></div>”);
    $('#ajaxLoading').load(pageURL +' #container', function() {$('#container').unwrap();});

  • http://twitter.com/buckmanhands Buck Manhands

    This really works well!! Thanks Nicholas. The cross-domain plugin mentioned below did not work for me, but this worked like a champ.

    One thing I did notice, when I returned the page, CSS that was written directly into the head of the loaded document was loaded even if I just chose to load a portion of the page as shown in the examples above.