Home / Loading content with jQuery AJAX

Loading content with jQuery AJAX

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.