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 to the jQuery API team.

* All fields are required
  • Stuart

    Be mindful of no cache in header with IE. Or use an inject of random number like
    $(“#objectID”).load(“test.php?n=”+random, { 'choices[]': ["Jon", "Susan"] } );

  • pete

    i think it is worth mentioning that some browsers don’t accept loading a page from another source. ie, in firefox you can’t use .load(“http://www.abc.com”); in safari it does seem to work.

  • pete

    further to this. it seems this is a client side security feature to prevent phishing.
    to get around this, i loaded the page from another domain on my server, then echoed it out. that way the domain stayed the same and the feature worked.

  • Cyp

    the load function does not grab script tags. it should grab everything.

  • Val

    It’s mentioned that only a “string” or a “map/object” can be used as the value for the data parameter but not an array. However, as load() calls ajax() and the latter transforms a data array into a query string, it should be mentioned here that data can also be an array.

  • 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.

  • http://twitter.com/melissabent Melissa Bent

    So, I think I’m correct in guessing that I cannot use this to inject an external html page into my website? I have files stored on S3 and have used CNAMEs to change the URL to my buckets to appear as subdomains. So, if my script is on http://www.site.com and I want it to pull http://download.site.com/file.html and inject the contents into my page it won’t because the Same origin policy won’t allow it?

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

    For more information about scripts and .load(), please refer to the forum thread:
    The “.load()” function and script blocks.

  • 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.

  • http://profiles.yahoo.com/u/WTQOV2X4NLIBWS2WHORUMZCKJQ YoungJedi

    Evidently, you are right. I wish they would state that right at the top. The definition implies you can pass any old URL, but that just plain doesn’t work. I was so frustrated by this until I found this answer on stackoverflow (http://stackoverflow.com/questions/763561/why-jquery-load-doesnt-work) and your comment.

  • Anonymous

    use .live() handler to bind events when you are using $.load(). read more about in events documentation

  • 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.

  • Anonymous

    when i load some content using .load() function some scripts which must work with loaded content didn’t work. what i doing wrong? thnx

  • 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.

  • Anonymous

    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)

  • 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.

  • http://www.joe-bowers.com 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.

  • http://digitaldeviation.com/ Justin Doles

    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.

  • Anonymous

    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….

  • Anonymous

    What to do when ajax page means which we are loading have js files and css files….

    bcz i am trying to to do load another page on in some function, thens its only loading simple file but not the js and css files….

    is this can be done through jquery or anything else?
    so how to do this?

  • Kris_mad007

    call your function into ajax success method…..
    like..
    $.ajax({
    //other options
    success:function(){
    yourFunction();
    }
    });

    hope it will be helpful……

  • dupledge

    why does it load all my external html page when I call it and not just the div I asked for
    e.g.

    I want to load only the contents inside the div with the ID of “RightColumn” so I used the following:
    $(“.contents_page span”).load(‘../products/products.html’+'#RightColumn’);

    yet it showed me all that was above this div as well?

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

    You need a space to separate the url and the selector:
    $(“.contents_page span”).load(‘../products/products.html’+’ #RightColumn’);

  • Anonymous

    right, cache mechanism needs some mechanism to work, like appending a GET var to the url, just a bit counterintuitive when doing a load via POST to have the url string modified.

    unsetting $_GET['_'] does the trick, I never pass underscored GET vars, but could break a 3rd party app that does.

    can’t complain too much, jQuery is absolutely AWESOME ;–)))

  • carloroosen

    It seems [data] must be a single html element (with or without children, but without sibblings). At least FireFox generates an error if you load 2 elements. If I encapsulate the 2 divs by another div this extra div is added into the DOM, which is not what I want. I tried a body tag, and it works, the body element is not included in the DOM, and no error is reported too. What is the official way?

  • carloroosen

    I mean, the return value, not [data]

  • carloroosen

    As noted before, Firefox (I didnt test other browsers) expects an XML root element as a return value for load(). As a result, you can never load several items in a container (say, several li elements in an ul). An option is to load the entire ul inside a parent div, but that means that, again, the ul must be the only child element of that div. Any comments or suggestions?

  • http://www.rodmanmx.hostzi.com RodManMx

    Hi everybody,

    I'm loading some dynamic content in php, the problem is that the content have some images that should open a modal window, (I'm usung jquery prettyBox), I've read that the loaded contente with load() function doesn't have the same properties, but I really need to pen thjat images with a modal window (it doesn't matter if is not the same), I tried to use live() but it didn't work… so, what can I do? Any ideas?

  • Vijai

    $(“#ok”).load(“announcement.txt”,function(){alert(“Successfully Loaded”);});

    The above query shows the msg “Successfully Loaded” when the file “announcement.txt” is missing in the folder also. How to check whether the file exists or Not before loading it to an HTML element using JQ?

  • Aric

    Pass args to your callback function and check to see if there actually was an error:

    $(“#ok”).load(“announcement.txt”, function(response, status, xhr) {

    if (status != “error”) {
    alert(“Successfully Loaded”);
    } else {
    alert(“Houston, we have a problem!”);
    $(“#ok”).html(“Whatever was here before…”);
    }

    });

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

    Look at the second example above.

  • 8W_gremlin

    I’m calling a a page with the .load function and its workign perfectly, however the page includes some inline JS tags and I need these to run (swfobject js) to create the SWF player.

    Any thougths on how I can get the JS to run?

    thanks

  • maodarin

    I’m problems is variable params send to server

    does not work
    param=$(this).attr(“param”);
    $(“#outbox”).load(“/ai/gator/_users_detail/”,{param: $(“#”+param).val()});break;

    and does not work

    $param=$(this).attr(“param”);
    $(“#outbox”).load(“/ai/gator/_users_detail/”,{$param: $(“#”+param).val()});break;

    and does not work

    param=$(this).attr(“param”);
    params=”{“+param + “:” + $(“#”+param).val() + “}”
    $(“#outbox”).load(“/ai/gator/_users_detail/”,params);break;

    what do to worked???

  • Aric

    You should target a file specifically with the load statement.

    What I’m assuming you’re doing is filling the contents of a div with id=”outbox” with the contents of /ai/gator/_users_detail/index.php, and sending parameters via POST method.

    The first line:
    var param = $(this).attr(“param”);

    Not sure what’s going on here. I’m assuming this is in a method for an event handler? I don’t know what you’re trying to accomplish here, but what this will do is return “number1″ if the element returned by $(this) looks something like . Even so, not sure it will actually work, since “param” isn’t a standard attribute for an HTML tag.

    Best thing would be to give each tag an id, then get that with the attr() method. Something like:

    I’m going to be clicked!

    then with jQuery:
    $(“div.clickable”).click(function(){

    var ajaxParameter = $(this).attr(‘id’);
    $(“#outbox”).load(“/ai/gator/_users_detail/responder.php”,{‘param’: ajaxParameter});

    });

    This will take the ID of the clicked div (as long as it belongs to the “clickable” class) and pass it to responder.php at the specified location. The PHP file will then process the POST parameters, then generate some output for you, and will then be loaded into the div with the id of “outbox”.

    Based on the limited amount of information you posted, I can’t really tell what you’re trying to accomplish, but I hope this helped you out some.

  • guest

    I found some encode problem when I need to load script with other encode.
    With script tag I can define charset attribute, while how can I do in jquery load()?

  • Dschinkel

    This page is decent but I don't think it's completely obvious by the wording on this page that in the example above “a callback function” is already there. And some don't just infer that function() is the callback here. The function() {alert('Load was performed.'); for example is the callback function in that example. Sure, to some it's obvious but it's not that obvious depending on how you read this page. There's not enough talk about the callback in my opinion..this page needs to be updated to be a little more less inferring and move obviously stated.

    So for example, here's how you'd use the callback function() above to check the responseText:

    $(“#orderList”).load(“OrderHandler.ashx?action=” + action + “&oid=” + “&orderIDs=” + orderIDs, function(responseText, textStatus, XMLHttpReques)
    {
    if(responseText == [however you want to check the response here])
    {
    // do something if responseText satisfies the check
    }

    // do something else
    });

    Keep in mind that responseText I believe will still send back any header info even if no data is sent back so checking for responseText.length will vary and you will get mixed results, probably normally the length will always be > 0… correct me if I'm wrong.

  • http://script-dev.com ivanhoe

    One not so obvious thing: If you've got global complete handler set
    $.ajaxSetup( {complete: function() { alert('done'); } );

    and then call load() with callback function, the above global handler will not get called at all

  • Kenny
  • kenny

    sorry aparently html is allowed before “tag” there should say a link tag : a

  • scribu

    Don't forget that load() is also an event handler shortcut. The following two lines are equivalent:

    $('some-selector').load(function() { // some code });

    $('some-selector').bind('load', function() { // some code });

  • Quespiry

    There is problem – Javascript doesnt work in loaded document. I have included javascript files in the header of index.php (javascripts on index.php page works well) and when I load any part of another document with .load() command, javascript doesnt work in loaded document.

    Any solutions how to get it to work?

  • Quannm

    i got the same problem.
    i seem like you can only load html content with ajax.

  • 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!

  • http://twitter.com/cistov Artur Cistov

    If you use traditional event binding ( eg. through .bind() or click() etc.), it won't work for any new elements loaded in via ajax. You should use delegate() or live() to keep your event handlers working in that case.

  • Csite_ir

    can we send a multipart/form-data to a php page , for example , for upload a file ???

    <FORM METHOD=”POST” ACTION=” do_upload.php” ENCTYPE=”multipart/form-data”>
    <INPUT TYPE=”file” NAME=”myfile”>

  • http://twitter.com/hivehicks Andrey Yutkin

    Why do this method uses POST instead of GET (according to Firebug)?

  • Omar_mtz

    wen i load (ñ,á,é,í,ó,ú), it don't work, anyone can helpme

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

    According to the documentation: “The POST method is used if data is provided as an object; otherwise, GET is assumed.”

  • Dhl0212

    I met the same problem and solve it with delegate function. I spent 1 week for googling. Thank you for your advice.

  • oompa_l

    is there a way to unload a page once unloaded? I found empty() but I want to return to preloaded state, not empty…

  • Roman
  • Christian Gnoth

    I am using the following jquery :

    var biq_select_val = jQuery(“#biq_search_select”).val();
    jQuery(“body”).load( window.location.href, {biq_amazon_item_list_search: biq_select_val});

    it is working on some pages, but in special construction not – it then do not reloads the page and the whole body tag is empty, but the §_POST['biq_amazon_item_list_search'] is send successfully.

  • SoccerMan

    Create a file holding the preloaded state then load then in whenever you want it to “empty()”

  • bubux

    I want to load a part of page which is selected by id. So I write
    $(“#news”).find(“h3:eq(0)”).load((“daty.php #data_0″)); everythig was ok until I added a lightbox script. This code doesn't work at all but when I put .myClass instead of #data_0 it works. Could you give me some clue where is the problem?

  • bubux

    $(“#news”).find(“h3:eq(0)”).load((“daty.php p[id='data_0']“)) I found a solution.

  • bubux

    $(“#news”).find(“h3:eq(0)”).load((“daty.php p[id='data_0']“)) I found a solution.

  • bubux

    $(“#news”).find(“h3:eq(0)”).load((“daty.php p[id='data_0']“)) I found a solution.

  • Shamsuljewel

    When the load is loading the page can i show a loading image in the div …

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

    how about .remove()?

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

    I'd recommend using Mike Alsup's form plugin for that.

  • Akarpy

    $('#lectures').load(url+' #content');

    Correctly works everywhere except Safari on Mac,PC,iPhone,iPad. Safari seems to load the page but then fails at parsing it to find #content. There is no javascript or styles within the page. Any ideas in regard to this? Can anyone else reproduce this?

  • http://pulse.yahoo.com/_RPVHR734DVN4TPQKDROKDPXL4E Dario Zadro

    Do you have an example using .delegate instead of .load? Thank you.

  • mistike

    I solved this by adding the new JS in the callback function :

    $(“#modified”).load(“/lib/ajx-src-latest.php”, {type: “modified”}, function(){$(“.popup”).popupWindow()});

  • Brent1221

    Im passing a URL string through PHP so my url is http://mysitehere.com/work.php?value=2

    The 2 is in reference to a div that I am then loading in through an external php file that has content.

    I only want to target that specific divs content and ignore the rest for now.w

    Is the a way to use my target value in the load feature?

  • Bigo77e

    Hello

    I wanted to see how I can use data in json format in a page loaded with the method $(…). load (page.html).

    I do what can be done with the prototype method and using the method Updater evalScripts and allow me to use the content that You will get a request made on another page

    var load = new Ajax.Updater (
    'DivContenedor'
    'View / vistaContenidoNuevo.php'
    (Method: 'get', parameters: peticion.responseText, evalScripts: true)
    );

    From already thank you very much

  • Stephanie

    I have an issue as follows: 2 users create a request to a page at almost the same time. Both requests seem to be processed (to start) correctly, but when the 1st returns the 2nd thinks that is its result as well. Kindof like the 2 requests turn into 1 request, and the 1st request determines the results for both.
    I use the .load function to call an .aspx page that retrieves data based on parameters sent. It then processes that data to create markup to pass back to be, obviously, loaded into the corresponding object.
    I have the function that executes the SQL synclocked (VB.NET), so I don't think that is the problem. I also added a synclock to the whole .aspx page, that didn't help (unless I did that wrong). Anyway, I think that if it was a problem of using the same variables it would return the 2nd request's results to both users.

    Any ideas? Thanks!!!

  • Stephanie

    I figured out what the problem was. I had the directive:
    <%@ OutputCache Duration=”1″ VaryByParam=”none” %>
    in my page. I should have had:
    <%@ OutputCache Duration=”1″ VaryByParam=”*” %>

    http://www.4guysfromrolla.com/articles/022802-1.aspx
    talks about it

    Hope this helps someone else!

  • mcp

    How can i force .load() to not go to the cache. Is there a force reload option? Every time i make a change to an html page that is loaded by load, my users have to clear their cache first in order to get the new content. Please help :)

  • Bth

    I’ve got the same question. I put

    in the header of the page i’m loading, and it seems to work most of the time.

    Would be nice to be able to force the no-cache load with load().

  • mcp

    unfortunately, meta tags are not always honored. I also put in code to force browser reloads using php and headers, but unfortunately, internet explorer doesnt seem to like those either.

  • http://twitter.com/chwcomputer Michael Wegener

    Just add an additional get parameter with an always changing value (time should do the trick).
    Example:
    timer = new Date();
    $('#my_element').load('/ajax_providex.php?param1=example&nocache=' + timer.getTime());

  • Flashmedias

    one simple question, please

    for the prototype string:
    new Ajax.Updater( '#comprobar_mensaje', url, { method: 'get', parameters: pars});

    the .load() function are?
    $('#comprobar_mensaje').load(url, pars);

  • ceevk1

    How do i go for calling a page in a new blank page instead of calling it inside a div though??

  • http://www.poetro.hu/ Poetro

    Use window.open instead.

  • Silenceisgolden

    I use thsi code to update some server side code without refreshing the entire page. i beleive this is similar to what your looking for. It's set to refresh every 60 seconds after initial page load

    $(document).ready(function() {
    $(“#unsch”).load(“/rz/rz-unsch.asp”);
    var refreshId = setInterval(function() {
    $(“#unsch”).load(“/rz/unrz-sch.asp”);
    }, 60000);
    });

  • AriderM

    If it’s an issue with PHP some googling can provide you with instructions on how to spit out a mime type. I had issues on a different project where I was loading pics I believe but the solution was to echo the html mime type before it began loading the picture. I might have it backwards though. In fact, I’m pretty sure php was spitting out standard html mime types but I needed jpeg. Either way, worth looking into.

  • http://nerkn.mornehir.com nerkn

    How can we force cache? I try to load a php page?

  • Lee

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

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

  • Bonnmos

    Is there a way to force the load() method to use http GET even if data is provided as an object?

  • http://twitter.com/testbvg Anggara

    why don't you use like this:

    $('#el_id').load('target.php?param=somedata&another=else #fragment');

  • bodomias

    Hi oompa_l. There is the unload() method. find it at http://api.jquery.com/unload/

  • http://www.serdan.co.za NINJA

    Can the .load() function get a portion of a page on another domain

    EXAMPLE:
    $('.nav').load('index.htm #navigation'); // THIS WORKS!!! (index being another page on my PC)
    $('.nav').load('http://www.anotherdomain.com #navigation'); // THIS DOESN'T WORK!!!

    Can anyone help?

    Also, the first example (that works) does not work in chrome, Any thoughts?

  • hopkinsju

    “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.”

  • 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://www.serdan.co.za Dan

    where can i get a comment system like this one to put on my website

  • paganaye

    People should be aware that while most of jquery works perfectly from the file system, Ajax commands like .load only work with a web server.
    IE: $('#result').load('ajax.html') won't work if you run it from 'file:///C:/html/page1.html'.

  • viddya

    In my test application I am using .load() as follows

    $(“mydiv”).load('test.html') it works fine in FF and Safari both from filesystem and website. But it does not work in IE.

    Do I need to change the load() like below to make it work in IE ?

    $(“mydiv”).load('http://hostname.domainname/<path>/test.html&#39 ;)

    Can you please advice ?</path>

  • underpaidNoob

    I wonder if anyone else has discovered this odd quirk: .ajax() with dataType: 'html' will serve an entire page in FF or IE (including scripts and css), but in Safari it only loads the html itself. Switching to .load() revealed another oddity: Safari doesn't like it when you give it html islands interrupting the PHP-generated response (in other words, ?>

    Not php

  • underpaidNoob

    …following comment above: solve this by using heredoc syntax whenever you need a long stream of just html (echo <<<eod and=”" on).=”" so=”"></eod>

  • Jack

    You can change the default ajax settings, which .load() uses. Example:

    $.ajaxSetup({cache:false})

  • http://www.kriest.de Rene

    You made my day. Thx for your comment! :)

  • Noreply

    $.ajaxSetup( {
    cache : false
    });

  • Mohan Prajapati

    Hello dear I have used the functionality of load method to load the page content or page fragment with custom plug in. please check it out and give some suggestion.

  • fr3ggel

    $.ajaxSetup({cache:false})

    this works for me in al 3 browser (ie, ff and chrome) tnx

    i now have this:

    $.ajaxSetup({cache:false})

    setInterval(“$('#ajax').load('http://domain/file.php&#39 ;) ”, 20000);

  • Simon

    That's bizarre, because it works well for me locally in IE(8), Safari, Opera and Firefox.

    Would someone be able to confirm what the potential issues here are?

  • I-am-will

    jQuery load will, due to setting the innerHTML, break any newlines in Internet Explorer in possible scenario's.

    See http://stud3.tuwien.ac.at/~e0226430/innerHtmlQuirk.html

  • Sathyak_1989

    function updateBids()
    {
    var url=”thread.php”;
    new=load(“thread.php”)
    }
    Is it possible to execute the thread.php file and store the returned value in new variable please help me….

  • Teste

    you should use the “get” or the “post” functions:

    http://api.jquery.com/jQuery.get/

    http://api.jquery.com/jQuery.post/

  • 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?

  • Estahbanati

    You'd better use get() method:
    $.get(“test.php”, { name: “John”, time: “2pm” } );

    Visit http://api.jquery.com/jQuery.get/ for more samples.

  • https://www.google.com/accounts/o8/id?id=AItOawnoXgT1xwGKJQmYmDerQd8SLofQ93TMKpo bozdoz

    window.open()?

  • jaz
  • 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…

  • 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.

  • 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();

  • 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

  • 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?

  • http://jestrade.tumblr.com Jes

    it works with Chrome correctly

  • 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?

  • 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 ��������

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

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

  • 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>

  • 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?

  • E. Hymel

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

  • 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.

  • 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.

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

  • 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.

  • Lopes80andre

    There are examples on how to do this?

    Best Regards.

  • Sumairz

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

    it is not returning anything

  • 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>

  • 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…

  • 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.

  • 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>

  • 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.

  • 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')
    }

  • 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,

  • Anton-ny

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

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

  • ManOVision

    Thanks…worked perfectly to disable the cache.

  • ac

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

  • 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.

  • Test

    dgfdgfg

  • Roodlokje

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

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

    how do can i load xml document and display it?

  • 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

  • Vasya

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

  • 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…