Home arrow AJAX & Prototype arrow Page 4 - Using Ajax and jQuery

Using jQuery and the Ajax "load" method - AJAX

In this tutorial, you will learn how to use the jQuery API to handle and process a plethora of Ajax requests. This article explores the jquery methods for using both get and post with AJAX and details the .get() and .load() methods.

TABLE OF CONTENTS:
  1. Using Ajax and jQuery
  2. Triggering POST requests via the “ajax()” method
  3. Using jQuery and the Ajax “get()” method
  4. Using jQuery and the Ajax "load" method
By: Alejandro Gervasio
Rating: starstarstarstarstar / 1
May 05, 2011

print this article
SEARCH DEV SHED

TOOLS YOU CAN USE

advertisement

Taking the final (and easiest) step: a quick look at the “load()” method

As noted before, I’d like to end up this humble roundup on the Ajax methods included with jQuery by showcasing the easiest one of all, which turns out to be “load()”. In case that its name doesn’t ring any bells to you, the “load()” method permits… yes to load the contents of an HTML file and place them within a specified web page selector.

Does this sound somewhat confusing to you? Fear not and look at the below example, which you’ll surely grasp in a snap:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="
http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Example using the 'load()' method</title>
<script type="text/javascript" src="
http://ajax.googleapis.com/ajax/libs/jquery/1.5.2/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function() {
    $('a').click(function(event) {
        event.preventDefault();
        $('#container').load('page.htm');
    });
});
</script>
<style type="text/css">
body {
    padding: 0;
    margin: 0;
    background: #5a2e2e;
    font: 0.8em Arial, Helvetica, sans-serif;
    color: #5a2e2e;
}
a {
    color: #5a2e2e;
}
#wrapper {
    width: 400px;
    margin: 0 auto;
    background-color: #fefdf1;
}
#header, #main, #footer {
    padding: 20px;   
}
</style>
</head>
<body>
<div id="wrapper">
    <div id="header">
        <h1>Example using the 'load()' method</h1>
        <h2>Header Section</h2>
        <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Suspendisse auctor commodo risus, et ultrices sapien vestibulum non. Maecenas scelerisque quam a nulla mattis tincidunt. Etiam massa libero, pharetra vel laoreet et, ultrices non leo. Lorem ipsum dolor sit amet, consectetur adipiscing elit. Sed posuere ullamcorper lacus et sollicitudin. Morbi ultrices condimentum lacus, sit amet venenatis purus bibendum sit amet.</p>  
    </div>
    <div id="main">
        <h2>Main Section</h2>
            <p><a href="page.htm">Load HTML file...</a></p>
            <div id="container"></div>
    </div>
    <div id="footer">
        <h2>Footer Section</h2>
        <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Suspendisse auctor commodo risus, et ultrices sapien vestibulum non. Maecenas scelerisque quam a nulla mattis tincidunt. Etiam massa libero, pharetra vel laoreet et, ultrices non leo. Lorem ipsum dolor sit amet, consectetur adipiscing elit. Sed posuere ullamcorper lacus et sollicitudin. Morbi ultrices condimentum lacus, sit amet venenatis purus bibendum sit amet.</p>  
    </div>
</div>
</body>
</html>

There you have it. See how easy is to fetch HTML contents with the “load()” method? I guess you do. In the example above, I took advantage of its functionality in order to grab a sample file called “page.htm” and dump it into a generic wrapper identified as “container” (yes, mi creativity with names sometimes is amazing), but the same driving logic can be applied to other selectors as well. And before I forget, here’s how the target “page.htm” file looks:

(page.htm)

<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Suspendisse auctor commodo risus, et ultrices sapien vestibulum non. Maecenas scelerisque quam a nulla mattis tincidunt. Etiam massa libero, pharetra vel laoreet et, ultrices non leo. Lorem ipsum dolor sit amet, consectetur adipiscing elit. Sed posuere ullamcorper lacus et sollicitudin. Morbi ultrices condimentum lacus, sit amet venenatis purus bibendum sit amet.</p>

Definitively, this example shows in a nutshell how simple is to put the “load()” method into action, even when its counterparts “get()” and “post()” can be a little more flexible, as they allow to grab content in different format, not only in HTML. But, hold on a second! In fact, I haven’t shown you yet the output that the previous example produces after invoking “load()” when clicking on the target link. Well, the following screen shot does exactly that:

Definitively, the “load()” method results particularly useful when it comes to fetching plain HTML, which is all well and fine. Nevertheless, it has an additional feature that you’ll fall in love with: when called with an extra argument appended to the specified URL, it will let you load web page fragments in a breeze.

For instance, if the previous “page.htm” file would be redefined like this:

<div id="section1">
    <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Suspendisse auctor commodo risus, et ultrices sapien vestibulum non. Maecenas scelerisque quam a nulla mattis tincidunt. Etiam massa libero, pharetra vel laoreet et, ultrices non leo. Lorem ipsum dolor sit amet, consectetur adipiscing elit. Sed posuere ullamcorper lacus et sollicitudin. Morbi ultrices condimentum lacus, sit amet venenatis purus bibendum sit amet.</p>
</div>
<div id="section2">
    <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Suspendisse auctor commodo risus, et ultrices sapien vestibulum non. Maecenas scelerisque quam a nulla mattis tincidunt. Etiam massa libero, pharetra vel laoreet et, ultrices non leo. Lorem ipsum dolor sit amet, consectetur adipiscing elit. Sed posuere ullamcorper lacus et sollicitudin. Morbi ultrices condimentum lacus, sit amet venenatis purus bibendum sit amet.</p>
</div>

Then, you could use “load()” to fetch only the contents wrapped within the “section1” div in the following way:

$(document).ready(function() {
    $('a').click(function(event) {
        event.preventDefault();
        $('#container').load('page.htm #section1');
    });
});

That’s pretty handy, isn’t it? And best of all, the implementation of the whole loading script required to write only a few lines of code. Of course, jQuery includes many other useful methods that will let you do some pre/post processing when sending Ajax requests. However, exploring these ones will be left as homework for you, something that will keep you entertained for long hours. 

Final thoughts

Undeniably, jQuery is a great tool when it comes to using the power of Ajax in an approachable fashion. So, armed with the bunch of code samples that you learned before, you should be able to build your own Ajax applications without having to deal with the complexities of raw JavaScript.

Either if you need to trigger GET or POST HTTP requests to load dynamically sections of a web page or simply validate user data in a more friendly way, the library has an Ajax method that surely will fit your needs, even if you’re a picky, highly demanding web designer.

See you in the next tutorial!



 
 
>>> More AJAX & Prototype Articles          >>> More By Alejandro Gervasio
 

blog comments powered by Disqus
escort Bursa Bursa escort Antalya eskort
   

AJAX & PROTOTYPE ARTICLES

- Best AJAX Tutorials for Forms
- The Best AJAX Tutorials
- 8 Great Ajax Tutorials
- Using Ajax and jQuery
- Using Ajax and jQuery with HTML Forms
- Ajax.org Offers Cloud9 IDE for JavaScript
- Java Technologies Provider ICEsoft Releases ...
- Using Recaptcha in AJAX Prototype Framework ...
- Google's Closure Compiler Service API: Addit...
- Installing Google Web Toolkit: Introducing t...
- Google's Closure Compiler Service API: Displ...
- Google's Closure Compiler Service API: Deliv...
- Google's Closure Compiler Service API: the A...
- Google's Closure Compiler Service API: the S...
- Google's Closure Compiler Service API: Optim...

Developer Shed Affiliates

 


Dev Shed Tutorial Topics: