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

Using jQuery and the Ajax “get()” 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

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. 



 
 
>>> 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: