.load() - The Layman's Ajax - Dynamic Website Content

January 27, 2011 — The .load() function is the simplest way to use Ajax and jQuery to dynamically load website content into your webpage. This tutorial explains features of the .load() method, other alternatives such as .get(), and assumes a basic understanding of jQuery.

.load() – Advanced

Besides simply loading dynamic website content into a <div> tag with jQuery's .load(), you can also load just a specific section of a page, define the webpage path with variables, and even pass URL paramaters in the address.

.load() Only a Specific Section of Content

If you only want to load a specific part of the page, you can add an element selector after the webpage path.

These will all load only a specific part of the page.
  1. $('#myDynamicDiv').load('mypages/pagetoload.html #contentDiv');
  1. $('#myDynamicDiv').load('mypages/pagetoload.html #mainCol .primaryDoc');
  1. $('#myDynamicDiv').load('mypages/pagetoload.html .article:first');

.load() Using Variables

You can also use a string variable that contains the path to the webpage or only part of the path, like the filename.

These will all load the same page, but use different variables
  1. $('#myDynamicDiv').load('mypages/'+myPage+'.html');
  1. $('#myDynamicDiv').load(myDirectory+'myPage.html');
  1. $('#myDynamicDiv').load(pathToMyPage+tplExtension);

.load() and Passing URL Parameters

The end of the URL can have parameters also. Consider combining several URL parameters into a single string, like example 3.

These will all load the same page, but pass different parameters
  1. $('#myDynamicDiv').load('mypages/pagetoload.html?item=519);
  1. $('#myDynamicDiv').load('mypages/pagetoload.html?news='+newsId+'&ver=1);
  1. $('#myDynamicDiv').load('mypages/pagetoload.html?'+urlParamString);

.load() Using Several Options

Finally, you can combine all these extra options together (you may produce cleaner code if you use the .get() method).

This will load only a specific part of the page using variables, and pass URL parameters to the page
  1. $('#myDynamicDiv').load('mypages/'+myPage+'.html?news='+newsId+'&'+urlParamString+' #mainCol .primaryDoc');

Add a Comment

Comments

Posted Subject Comment
Sanjeewa
November 21, 2011
Call the above .load() func... Hi,

I'm new to AJAX and JS. So, please consider this in that context.

What I want to know is, how can I call the above load function from within an HTML link (href). For example, I have a link like this <SERVICES>. How do I call the load function from within that href so that when I click the "services" link, it will load a div tag from the services.html file?

Thanks in advance,
Cheers
Marco
August 05, 2011
Solutions for travel web In my web http://www.ole.travel I want to include ajax in search, but only show view of article, before of go to web.