How do I load data with jQuery? In this tutorial, we're going to grab data from one page and display it on another. You can download the sample solution at the end of this tutorial. First, View The Example. In this example, you'll need to create two pages. Title the first one - "loadData.htm", and name the second one - "theOtherPage.htm".
The Page That We'll Grab The Data From
To get started, we're going to create our sample data in our "theOtherPage.htm" page. For the sake of simplicity, I've created an unordered list that contains my favorite movies.
<li style="font-weight: bold; list-style-type: none;">My Favorite Movies</li>
<li>Back To The Future</li>
There isn't anything too special here. The only thing worth noting is that we gave an ID to our unordered list - "favoriteMovies".
The Page That Will Do The Grabbing
The next step is to create our "loadData.htm" page.
<a href="#" id="loadData">Click This Link To Load My Favorite Movies</a>
This is the extent of our main page. We have a division that contains one link with an id of "loadData". When the user clicks this link, we are going to run some code that will fetch the data from the "theOtherPage.htm" page.
$(this).text("...One Moment Please...");
.load("theOtherPage.htm ul#favoriteMovies", function()
From top to bottom - When the document is ready to be manipulated, we are to grab the anchor tag with an id of "loadData". When this tag is clicked, we are going to run a function. First, we'll change the text property of the anchor tag to notify the user that the information is currently loading (even though it technically isn't yet). Then will grab our "container" div and add a new div as its child. We'll call this new div "favoriteMovies". Next, we are going to hide this new div until the data has completely loaded.
The Load() Method
The ".load" method is what actually fetches the data for us. Here, we are specifying, in the parenthesis, a path. This path goes directly to the "theOtherPage.htm". It then finds the unordered list with an id of "favoriteMovies"...and grabs that data. After that data has been retrieved, we are going to run a callback function. Callback functions run after a method has completed. This function will simply remove the anchor tag - we obviously don't need this link once our new div has been populated. The final step is to slowly slide our new "favoriteMovies" div down (remember, we hid it earlier while the data was loading!).
I hope this helped. I gotta go have lunch with Allie....ahh the hardships of working on your own. :)