Loading content with jQuery AJAXLoading 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:

Share or Bookmark

Share or Bookmark this page using the following services. You will need to have an account with the selected service in order to post links or bookmark this page.

Subscribe or Follow

Subscribe via RSS or email, or follow me on Facebook or Twitter below. The RSS icon takes you through to Feedburner where you can select the service or application to use.

Comments

blog comments powered by Disqus