Load remote content into div element using jQuery

. Wednesday, June 11, 2008
  • Agregar a Technorati
  • Agregar a Del.icio.us
  • Agregar a DiggIt!
  • Agregar a Yahoo!
  • Agregar a Google
  • Agregar a Meneame
  • Agregar a Furl
  • Agregar a Reddit
  • Agregar a Magnolia
  • Agregar a Blinklist
  • Agregar a Blogmarks

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:

Anonymous said...

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

Abhisek said...

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

Fahad Ibnay Heylaal said...

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

debers said...

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

Derpantzerfaukt said...

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

Fahad Ibnay Heylaal said...

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

Derpantzerfaukt said...

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

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

Fahad Ibnay Heylaal said...

exactly...

Anonymous said...

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!

Fahad Ibnay Heylaal said...

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

Anonymous said...

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

Fahad Ibnay Heylaal said...

please see the comments above. it will help.

scacsa said...

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

Anonymous said...

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.

charlyBraun said...

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

Anonymous said...

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

Unknown said...

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,

Mighy Alex said...

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

Anonymous said...

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

Anonymous said...

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?

Anonymous said...

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

Anonymous said...

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

Ricardo said...

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

TGMC said...

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"]

Ben said...

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?

john bailo said...

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?

Anonymous said...

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.

Jordi Hernández said...

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!

Anonymous said...

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

ScottInNH said...

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

Anonymous said...

Thank you for tutorial

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

Anonymous said...

$("#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

Kaiz said...

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

atasözleri said...

This is doesnt work for security issues!

Can anyone help me!

Anonymous said...

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.

Unknown said...

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

Anonymous said...

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

Anonymous said...

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!

Anonymous said...

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.

Anonymous said...

AWESOME. THANK YOU.

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

Anonymous said...

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.

Ranga said...

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

Anonymous said...

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

This works great BTW. Thanks!

Anonymous said...

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.

J.C. Hendee said...

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?

Anonymous said...

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

Anonymous said...

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.