Loading content with jQuery AJAX
Posted January 14th, 2009 in Javascript
With jQuery it is simple to load content with AJAX and inject it into the current web page using the .load() function. This post shows a basic example doing this. Future posts will look at some other ways of loading content and making AJAX requests with jQuery. Make sure to sign up to my RSS feed (see after the end of this post for details) so you don't miss out!
If you had some HTML that looks like this:
<p id="foo">Existing content that will be replaced.</p>
Then you could load some content using AJAX with jQuery to replace the text between the <p> tags like this (note that you have to of course included the jQuery library in your webpage):
$('#foo').load('/path/to/foo.html');
The text returned from /path/to/foo.html would be injected into the webpage into the <p id="foo"> tag replacing the existing content. You could just as easily load it into an empty <div> placeholder using the same Javascript above:
<div id="foo"></div>
Note that if an error occurs, such as not being able to connect to the server to get the web page, or the file requested does not exist, then nothing will appear to have happened and no error will be reported using the above example. I will look at how to do this in a later post in this series of jQuery posts.
Also note that the content loaded in this way should not be a regular webpage - just the content you actually want to load. If you load a full webpage with <html> <script> etc tags in it, unexpected consequences could happen which could lead to the resulting page being unusable.
It is possible to load an entire webpage and just inject part of the DOM into your current webpage. I will show how to do this in the next jQuery/Javascript post on Sunday.
Related posts:
- Loading content with jQuery AJAX and dealing with failures (Friday, February 6th 2009)
- Loading content with jQuery AJAX - using a loading image (Tuesday, February 3rd 2009)
- Loading content with jQuery AJAX - selecting the element to inject (Sunday, January 18th 2009)
- How to tell if it's an AJAX request in PHP (Monday, January 12th 2009)
- Dynamically get and set an elements content with jQuery (Sunday, January 11th 2009)
- How to get and set form element values with jQuery (Thursday, November 13th 2008)

Comments
blog comments powered by Disqus