Wednesday, June 11, 2008

Load remote content into div element using jQuery

If you are building rich web applications, then you will obviously require some ajax to give your users a smooth browsing experience. And jQuery makes it easier for you to do that without any trouble.

In my previous articles, I have shown you how to toggle a div element and also changing its content. Now I will show you how to load content from an external file into a div element.

loadContent() function
Though most of the jQuery code is placed inside head tag, I prefer that you create an additional javascript function for managing inline anchor links quickly.
function loadContent(elementSelector, sourceUrl) {
$(
""+elementSelector+"").load("http://yoursite.com/"+sourceURL+"");
}

This is the main jQuery code for loading remote content inside an element
$("#content").load("http://yoursite.com/source.php");

Usage
<a href="javascript:loadContent('#content', 'source_page.php');">Link 1</a>
<div id="content">content will be loaded here</div>

Final code
<html>
<head>
<title>jQuery test page</title>
<script src="jquery.js" type="text/javascript"></script>
<script type="text/javascript">
function loadContent(elementSelector, sourceUrl) {
$(
""+elementSelector+"").load("http://yoursite.com/"+sourceURL+"");
}
</script>
</head>
<body>
<a href="javascript:loadContent('#content', 'source_page.php');">Link 1</a>
<div id="content">content will be loaded here</div>
</body>
</html>

47 comments:

  1. Hey thanks man this was very helpful to me.could u please tell me how to add loader in this?So,that it could be displayed to the user when the remote content is being loaded.
    Thanks

    ReplyDelete
  2. Does it work with the cross domain content?
    Nice blog, btw!

    ReplyDelete
  3. in loadContent() function, try changing yoursite.com to something else. it should work.

    ReplyDelete
  4. Hi, please note the small typo: "sourceUrl" in the declaration vs. "sourceURL" in the implementation!

    ReplyDelete
  5. if someone went to http://www.yoursite.com (instead of http://yoursite.com) it doesn't work. how can you fix this?

    ReplyDelete
  6. its better to include 'www' in your url then. i created the loadContent() function for the simplication of code inside the BODY tag.

    or you can even edit the function so that you enter the complete remote url.

    function loadContent(elementSelector, sourceUrl) {
    $(""+elementSelector+"").load(""+sourceURL+"");
    }

    ReplyDelete
  7. oh, just get rid of the yoursite.com part so it's:

    function loadContent(elementSelector, sourceURL) {
    $(""+elementSelector+"").load(""+sourceURL+"");
    }

    ReplyDelete
  8. Is it possible to also add an anchor tag to the link in order to move the page to where the div tag that's loading the external file is positioned?

    See, I'm working on this horizontally oriented website and I want to have a link in the main menu not only load content into a div that's in the third section but also move the browser page to that section at the same time.

    Thanks for any help!

    ReplyDelete
  9. have a look at ScrollTo plugin of jQuery. probably that will help.

    ReplyDelete
  10. Sorry, but this does NOT work with the cross domain content.

    ReplyDelete
  11. please see the comments above. it will help.

    ReplyDelete
  12. this does not work in Firefox,

    $("#div1").load("http://www.somesite.com/somepage.aspx");
    Error: [Exception... "Access to restricted URI denied" code: "1012" nsresult: "0x805303f4 (NS_ERROR_DOM_BAD_URI)"

    only in IE 7 and also with errors

    I had to call C# page method and then parse the string in C# and return it to ajax call to load into div
    you need code - tell me

    ReplyDelete
  13. thanx very much, i almost thought cross domain loding isnt possible at all due to some comments i found in other sites. This code is fine for IE. But it didnt work for me in opera or mozilla.

    ReplyDelete
  14. Hi, I used your code on a personal page I'm working on... but it doesn't evaluate the js code inside the page it loads. Could you please tell me how to do this?

    Thanks a lot!!!

    ReplyDelete
  15. Alexey:
    Are you running the script on you local machine? Try uploading to a server and the error message should disappear.

    ReplyDelete
  16. Ey man,

    Do you know make it not buffer any of the data returned. I am using this code to load some data that takes about 1 min to load, and i dont want it to buffer the data, i just want it to return it all as it gets the data.

    Cheers,

    ReplyDelete
  17. It doesn't work cross domain :( please help...

    ReplyDelete
  18. How do you close it out? or clear it? when they click on anything other than the div box?

    ReplyDelete
  19. Thank you for this tutorial!
    Firebug Error:

    sourceURL is not defined
    [Break on this error] $(""+elementSelector+"").load("http://127.0.0.1/jQuery/"+sourceURL+"");

    Any suggestions?

    ReplyDelete
  20. Change "sourceURL" to "sourceUrl" according to the argument name of the function.

    ReplyDelete
  21. Thanks, I changed "sourceURL" to "sourceUrl" and it worked like a charm!!

    ReplyDelete
  22. I'm having some issues with my character set when using this code. How can this be solved?

    ReplyDelete
  23. Works well with local pages.

    But for remote php page, i got this. Am i doing mistake. Help me

    Error: uncaught exception: [Exception... "Access to restricted URI denied" code: "1012" nsresult: "0x805303f4 (NS_ERROR_DOM_BAD_URI)" location: "http://localhost/download/test/jquery.js Line: 3517"]

    ReplyDelete
  24. If I load a html with absolute positioned divs into a relative positioned div with jquery it gets messed up. What must I take care of, to load content properly?

    Are there any articles?

    ReplyDelete
  25. If I try to load a PDF document into the DIV, it renders as binary...is there any way to tell the DIV what MIME type to expect?

    ReplyDelete
  26. I have an issue, where i use an ASP treeview component, that incorporates a sitemap.

    but when i change to a sup menu, while a page is open that uses this script through the "load" event in an ajax eventhandler, the "foreign" url is loaded instead of my sites URL.

    I can for the life of me not figure out how to circumvent the postback event from the treeview submenu opening, that causes the page to shift to the foreign url.

    ReplyDelete
  27. Great tutorial and very useful.

    There is a little mistake on the code...

    function loadContent(elementSelector, sourceURL) {
    $(""+elementSelector+"").load("http://pennandteller/test/"+sourceUrl+"");
    }


    SourceUrl shoud be SourceURL or there is a conflict when executing.

    Thanks again!

    ReplyDelete
  28. Thanks, tried this and worked like gold on my second attempt. After googling and googling thought will never get a solution to this.

    And it's pretty fast too.

    cheers

    ReplyDelete
  29. I hit several problems so I thought I would document them, for benefit of other newbies.

    1) Fix SourceUrl to SourceURL
    2) VERIFY you are loading the jquery.js library. If you just Copy and Paste the example code onto your server.. and your server's jquery file is "jquery-1.3.2.min.js"... then the JS will fail to load.

    If you started incrementally adding this code to your existing script and got some unrelated error, and then copy/pasted the example code in desperation.. you'll be creating a new error and that may not be obvious if you are tired!

    3) You CAN'T load third party web content this way... the browser security stuff won't let you.

    However there is a workaround: Just make a PHP script on the server that will remotely fetch the content you want to load, and print it out. It will appear as if the content is "local" to the same server. No problems at all doing this...

    ReplyDelete
  30. Thank you for tutorial

    موقع زيروجيت
    0gate
    http://0gate.com

    ReplyDelete
  31. $("#div1").load("http://www.somesite.com/somepage.aspx");
    Error: [Exception... "Access to restricted URI denied" code: "1012" nsresult: "0x805303f4 (NS_ERROR_DOM_BAD_URI)"


    Use getJSON , its OK

    ReplyDelete
  32. hi.. can you tell me how to unload the loaded content?

    ReplyDelete
  33. This is doesnt work for security issues!

    Can anyone help me!

    ReplyDelete
  34. Can someone help me. I tried a lot of different codes to load external URLs into a div and nothing works! This is driving me creazy.

    I tried different codes and it is not working. I tested the codes in front page and it loads the page. I tried on my website and it is not working. What is causing such behavior.

    ReplyDelete
  35. Just one word: GREAT!
    It resolved my problem after hours of frustrating searches!
    And it works great with cross-domain!

    ReplyDelete
  36. Can anyone post a "final code" version of this... can't seem to get it.

    ReplyDelete
  37. Hi, I have used this solution, but I always have the same response from IE8: this is "access denied". Is there another solution to load a remote php page into a html local domain?.

    Thanks for any help!

    ReplyDelete
  38. Hi,
    Thanks for the tutorial.
    heres my code:

    $("#state").change(function(){
    $("#list_suburb").load("" + "/" + $('#state').val());
    });


    $("#list_suburb").load("" + "/" + $('#state').val() + "/");


    but this does not seem to be working in IE7.

    Please help me out..
    Thanks in advance.

    ReplyDelete
  39. AWESOME. THANK YOU.

    I've been pulling my hair out for days trying to figure this out, and this solution is so simple.

    ReplyDelete
  40. Why doesn't this work?
    <-form- method="get" action="javascript:loadContent('#content','test_this.php?number=');" enctype="multipart/form-data">

    <-select- name="number" onchange="this.form.submit()">
    <-option->Pick one:
    <-option- value="20" >20
    <--option- value="30" >30
    <-option- value="40" >40


    Since this site doen't accept form tages I added the -form- & -select- etc.

    ReplyDelete
  41. It is not working for me.
    Always throws security error.

    ReplyDelete
  42. How would I go about loading the content on the page load?

    This works great BTW. Thanks!

    ReplyDelete
  43. I can get the one HTML page to load into another but I end up with scroll bars. How to I tell the DIV to expand for the content. I tried everything and nothing works.

    ReplyDelete
  44. About cross domain loading... I have heard that some have gotten this to work by first loading the REAL external content (external to the domain) into a hidden iframe, then access it's page/body content to then transfer to the appropriate DIV. Has anyone here tried this and then used ajax to load that content?

    ReplyDelete
  45. Earlier i asked about php code doesnt execute, but never mind it's working like a charm. Thanks. You are awesome.

    ReplyDelete
  46. I just wanted to tell you I was looking for this very thing for like 4 hours and finally someone answers it correctly. THANK YOU so much.

    ReplyDelete