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

Triggering POST requests via the “ajax()” 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

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.



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