Using Ajax and jQuery

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.

There’s no shortage of options when it comes to leveraging the power of Ajax with jQuery, as the library includes a decent number of methods which allow you to trigger different types of HTTP requests, such as GET and POST (to name a few), and parse the corresponding responses via callback functions.

Having said that (and assuming you’re interested in learning how to take advantage of the functionality provided from the Ajax/jQuery tandem), in the course of this article I’m going to develop some comprehensive, fully-customizable examples aimed at demonstrating how to employ the aforementioned methods.

Getting started: using the “ajax()” method

As explained in the introduction, jQuery permits you to work with Ajax in a really simple and approachable fashion, thanks to the bunch of methods that it provides beneath the hood. With that being said, the first method that I plan on discussing here is called “ajax()”, which can be used for triggering different types of requests.

Of course, the best way to showcase the functionality of this method is by example, so below I coded one that demonstrates how to load the contents of a simple text file via a GET request. Take a look at it:   

<!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 'ajax()' 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();
        $.ajax({
            type: "GET",
            url: "data.txt",
            error: function() {
                $('#container').html('Error loading the target file.');
            },
            success: function(data) {
                $('#container').html(data);
            }
        });
    });
});
</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 'ajax()' 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="data.txt">Load text 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>

As shown in the previous example, using the “ajax()” method is a straightforward process that can be tackled with minor hassles, as the only arguments that the method require are the type of request that will be triggered (in this case GET), then the URL, and optionally the couple of callback functions that will be invoked if the request eventually fails or succeeds.

Now, suppose that the text file being loaded has the following definition:    

(data.txt)

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.

If, at this point, you give the prior example a try using your own browser, when clicking on the sample link you should get an outcome similar to the one depicted by the image below:

That worked like a charm, indeed! And best of all, the text file will remain accessible even if JavaScript is disabled in the browser. What more can you ask for?

Well, in fact the “ajax()” method can be used for performing POST requests with the same ease as it does with a GET one. And to prove the veracity of my claim, in the coming section I’ll be setting up a brand new example which will demonstrate how to submit and validate an HTML form using the method in question.

{mospagebreak title=Triggering POST requests via the “ajax()” method}

If you had the chance to take a peek at jQuery’s official documentation, you’ll probably know that its “ajax()” method can be used for sending POST requests with minor modifications. Even though utilizing the method is a simple process, by far the most challenging requirement is to show how to use it in a realistic scenario. With that idea in mind, below I created a whole new example, which illustrates how easy it is to validate the data entered in a sample contact form.

Here’s the (X)HTML page that renders the form and displays the errors that may have been raised during the validation process:

<!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 'ajax()' method (triggering a POST request)</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() {
    $("form").submit(function(event) {
        event.preventDefault();
        $.ajax({
            type: "POST",
            url: "form.php",
            data: ({subject: $("#subject").val(), email: $("#email").val(), comments: $("#comments").val()}),
            error: function() {
                $("#errors").html('Error submiting the form.');
            },
            success: function(msg) {
                // display the errors returned by server side validation
                $("#errors").html(msg);
            }
        });
    });
});
</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;   
}
form {
    padding: 30px;
}
form fieldset {
    border: none;
}
form fieldset ol {
    list-style: none;
    padding: 0;
    margin: 0;
}
form fieldset ol li {
    margin-bottom: 10px;
}
form fieldset ol label {
    display: block;
    margin-bottom: 5px;
    font-weight: bold;
    text-transform: capitalize;
    color: #5a2e2e;
}
form fieldset ol label em {
    font-style: normal;
    font-weight: normal;
    color: #5a2e2e;
}
form fieldset ol input.text {
    width: 250px;
    border: 1px solid #5a2e2e;
}
form fieldset ol textarea {
    width: 250px;
    border: 1px solid #5a2e2e;
}
/* error messages */
.error {
    color: #f00;
}
</style>
</head>
<body>
<div id="wrapper">
    <div id="header">
        <h1>Example using the 'ajax()' method (triggering a POST request)</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>Sample form</h2>
        <form action="form.php" method="post">
            <fieldset>
                <ol>
                    <li>
                        <label for="subject">subject: <em>[required]</em></label>
                        <input type="text" name="subject" id="subject" class="text" />
                    </li>
                    <li>
                        <label for="email">email: <em>[required]</em></label>
                        <input type="text" name="email" id="email" class="text" />
                    </li>
                    <li>
                        <label for="comments">comments:</label>
                        <textarea rows="10" cols="20" name="comments" id="comments"></textarea>
                    </li>
                    <li>
                        <input type="submit" name="send" value="Submit" />
                    </li>
                </ol>
            </fieldset>
        <div id="errors"></div>
        </form>
    </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>

As you can see, once the target form is submitted, the event is captured with jQuery and the entered data is sent out to a file called “form.php”, which performs the actual validation.

If you’re curious to see how this file looks, here’s its source code:

<?php

// get the values entered in the form (sanitization/filtering is required)
$subject  = $_POST['subject'];
$email    = $_POST['email'];
$comments = $_POST['comments'];
$errors = array();

// check if the 'subject' field is empty
if (empty($subject)) {
    $errors[] = 'Enter a subject for your inquiry!';
}
// check if the 'email' field contains a well-formatted email address
if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
    $errors[] = 'Enter a valid email address!';
}
if (empty($errors)) {
    echo 'Thank you for contacting us!';
    // do something useful with the form data here
}
else {
    // otherwise display validation errors
    echo implode('<br />', $errors);
}
?>

In this particular case, I decided to use PHP to validate the form at a very basic level, but it’s possible to utilize any other server-side language and get similar results. But wait a second! Still I haven’t shown you what happens if the form is submitted with an offending field. Well, look at the following image, which recreates this situation: 

There you have it. In a few easy steps, you learned how to use the “ajax()” jQuery method, in order to validate an HTML form via a POST request. So, what’s the next step that must be taken now? Well, even when “ajax()” can be used for sending distinct HTTP requests, jQuery includes two complementary methods, called “get()” and “post()”, which not surprisingly permit to trigger GET and POST requests via a dead simple interface. Considering this, in the following section I’ll be showing how to use the former, so that you can grasp its driving logic and put it to work for you in no time.

{mospagebreak title=Using jQuery and the Ajax “get()” method}

As I expressed in the earlier section, jQuery packages a method called “get()”, which allows you to dispatch GET requests without dealing with the complexities exposed by its cousin “ajax()”. As usual, the best manner to demonstrate how to use this method is by example, so below I recreated the one coded at the beginning, which this time fetches the contents of the same “data.txt” file via the method in question:

Here’s how this revamped example looks:

<!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 'get()' 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();
        $.get('data.txt', function(data) {
            $('#container').html(data);
        });
    });
});
</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 'get()' 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="data.txt">Load text 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>

If all works as expected, you should get output pretty similar to the one shown by the following screen capture:

The question that probably will be spinning in your mind right now is if its counterpart “post()” is that easy to use. Fortunately, the answer is a resounding yes! And to give you concrete proof of my claim, in the next section I’ll be teaching you how to validate the previous HTML form (remember that one, right?) but this time through the handy “post()”.

POSTing things in the server: working with the “post()” method

In reality, validating the previous sample form with the “post()” method is even simpler than doing the same with “ajax()”. Again, the most effective way to demonstrate this is with a hands-on example. So, take a close look at the one coded below, which utilizes the same “form.php” file to validate the data inputted in the target form: 

<!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 'post()' 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() {
    $("form").submit(function(event) {
        event.preventDefault();
        $.post("form.php", {subject: $("#subject").val(), email: $("#email").val(), comments: $("#comments").val()},
            function(msg) {
                // display the errors returned by server side validation
                $("#errors").html(msg);
            }
        );
    });
});
</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;   
}
form {
    padding: 30px;
}
form fieldset {
    border: none;
}
form fieldset ol {
    list-style: none;
    padding: 0;
    margin: 0;
}
form fieldset ol li {
    margin-bottom: 10px;
}
form fieldset ol label {
    display: block;
    margin-bottom: 5px;
    font-weight: bold;
    text-transform: capitalize;
    color: #5a2e2e;
}
form fieldset ol label em {
    font-style: normal;
    font-weight: normal;
    color: #5a2e2e;
}
form fieldset ol input.text {
    width: 250px;
    border: 1px solid #5a2e2e;
}
form fieldset ol textarea {
    width: 250px;
    border: 1px solid #5a2e2e;
}
/* error messages */
.error {
    color: #f00;
}
</style>
</head>
<body>
<div id="wrapper">
    <div id="header">
        <h1>Example using the 'post()' 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>Sample form</h2>
        <form action="form.php" method="post">
            <fieldset>
                <ol>
                    <li>
                        <label for="subject">subject: <em>[required]</em></label>
                        <input type="text" name="subject" id="subject" class="text" />
                    </li>
                    <li>
                        <label for="email">email: <em>[required]</em></label>
                        <input type="text" name="email" id="email" class="text" />
                    </li>
                    <li>
                        <label for="comments">comments:</label>
                        <textarea rows="10" cols="20" name="comments" id="comments"></textarea>
                    </li>
                    <li>
                        <input type="submit" name="send" value="Submit" />
                    </li>
                </ol>
            </fieldset>
        <div id="errors"></div>
        </form>
    </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> 
  
  


(form.php)

<?php

// get the values entered in the form (sanitization/filtering is required)
$subject  = $_POST['subject'];
$email    = $_POST['email'];
$comments = $_POST['comments'];
$errors = array();

// check if the 'subject' field is empty
if (empty($subject)) {
    $errors[] = 'Enter a subject for your inquiry!';
}
// check if the 'email' field contains a well-formatted email address
if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
    $errors[] = 'Enter a valid email address!';
}
if (empty($errors)) {
    echo 'Thank you for contacting us!';
    // do something useful with the form data here
}
else {
    // otherwise display validation errors
    echo implode('<br />', $errors);
}
?>

As shown above, the “post()” method has a tighter, shorter syntax than “ajax()”, and it permits you not only to dispatch POST requests with the same ease, but to handle erroneous and successful conditions via callback functions as well. Moreover, if you’re interested in seeing the results generated by the previous example, the image below should be quite illustrative:

So far, so good. At this stage, I’m sure that you’re on the right path when it comes to using the most relevant Ajax methods provided by jQuery. However, the library offers an additional one, which you’ll find a breeze to work with due to its flat learning curve and tight syntax.

In this case, I’m making reference to the “load()” method, and in the following section I’ll be setting up a final example that will show you how to use it in a concrete use case. 

{mospagebreak title=Using jQuery and the Ajax “load” method}

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!

[gp-comments width="770" linklove="off" ]

antalya escort bayan antalya escort bayan Antalya escort diyarbakir escort