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

Validating User Data with jQuery, Ajax, and PHP - AJAX

Being by far the most popular JavaScript framework available nowadays, jQuery generously honors its “write less, do more” motto. Seated on top of its already famous fluent API, the library provides a plethora of methods that allow you to perform many tasks, ranging from complex DOM and CSS manipulation, to handling events in a painless and straightforward manner.

TABLE OF CONTENTS:
  1. Using Ajax and jQuery with HTML Forms
  2. Validating User Data with jQuery, Ajax,
By: Alejandro Gervasio
Rating: starstarstarstarstar / 4
April 21, 2011

print this article
SEARCH DEV SHED

TOOLS YOU CAN USE

advertisement

Validating the previous contact form is a two-step process that covers both the server and client sides. Since the form’s “action” attribute points to a file called “processform.php”, the first thing that needs to be done is to validate the required fields with PHP.

To keep the whole validation process uncluttered and easy to follow, the definition of the mentioned PHP file will be this simple:

(processform.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 'Congratulations! The form was submitted successfully.';
    // do something useful with the form data here (send an email confirmation, etc.)
}
else {
    // otherwise display validation errors
    $errors = array_map(function($v){return '<p class="error">' . $v . '</p>';}, $errors);
    echo implode('', $errors);
}
?>

As you can see, the above PHP script performs some basic validation on the required form fields and displays the corresponding error messages at the appropriate places (needless to say that you should always sanitize and filter user input before processing any GET/POST data).

With this server-side script up and running, the form will be effectively submitted and checked, at least at a basic level. The question that comes up here is: where does jQuery/Ajax fit into this scheme? Don’t feel concerned, and take a peek at the following snippet, which validates the required fields with jQuery and submits the form via the library’s “ajax()” method:

(js/form.js)

$(document).ready(function() {
    $("form").submit(function(event) {
        // validate the 'subject' field
        if ($("#subject").val() == "") {
            $("#errors").html('<p class="error">Enter a subject for your inquiry!</p>');
            $("#subject").focus();
            return false;
        }
        // validate the 'email' field
        if ($("#email").val().indexOf("@") == -1) {
            $("#errors").html('<p class="error">Enter a valid email address!</p>');
            $("#email").focus();
            return false;
        }
        // send the form via Ajax
        event.preventDefault();
        $.ajax({
            type: "POST",
            url: "processform.php",
            data: ({subject: $("#subject").val(), email: $("#email").val(), comments: $("#comments").val()}),
            error: function(msg) {
                $("#errors").html(msg);
            },
            success: function(msg) {
                // display the errors returned by server side validation (if any)
                if (msg.indexOf('Congratulations') == -1) {
                    $("#errors").html(msg);
                }
                // otherwise, display a confirmation message
                else {
                    $("form").html('<h3>' + msg + '</h3>');
                }
            }
        });
    });
});

There you have it. Thanks to the implementation of this additional behavioral layer, the contact form will be checked with jQuery and, if no errors are found, the data will be submitted via Ajax to the previous “processform.php” file.

This shows how easy it is to complement the functionality of jQuery with the one provided by PHP or any server-side language. And best of all, the form will be validated even if JavaScript is disabled in the browser. We get the best of both worlds!

Of course, if you’re anything like me, surely you’ll want to see the finished version of this form validation script, so that you can test it and add to it your own tweaks.

Putting all the pieces together: showing the final version of the script

As I said in the previous segment, here’s the full source code of the form checking script, starting with the web page that includes the form in question:

<!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>Processing an HTML form with jQuery</title>
<script type="text/javascript" src="
http://ajax.googleapis.com/ajax/libs/jquery/1.5.1/jquery.min.js"></script>
<script type="text/javascript" src="js/form.js"></script>
<link rel="stylesheet" type="text/css" href="css/base.css" />
</head>
<body>
<div id="wrapper">
    <div id="header">
        <h1>Processing an HTML form with jQuery</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="content">
        <h2>Contact form</h2>
        <form action="processform.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>


(css/base.css)

/* layout and heading styles */
body {
    padding: 0;
    margin: 0;
    background: #000;
    font: 0.8em Arial, Helvetica, sans-serif;
    color: #fff;
}
h1 {
    font-size: 4.5em;
    text-shadow: 0 0 4px #3e1f00;
}
h2 {
    padding-bottom: 10px;
    margin: 0 0 30px 0;
    font-size: 3em;
    color: #ff8040;
    border-bottom: 1px solid #ff8040;
    text-shadow: 0 0 4px #3e1f00;
}
h3 {
    font-size: 1.5em;
    color: #fff;
}
#wrapper {
    width: 600px;
    margin: 0 auto;
    background: #773c3c;
}
#header, #content, #footer {
    padding: 20px;
}
/* form styles */
form {
    padding: 30px;
    background: #773c3c;
}
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: #fff;
}
form fieldset ol label em {
    font-style: normal;
    font-weight: normal;
    color: #ff8040;
}
form fieldset ol input.text {
    width: 250px;
    border: 1px solid #ff8040;
}
form fieldset ol textarea {
    width: 250px;
    border: 1px solid #ff8040;
}
/* error messages */
.error {
    color: #f00;
}

Done. Now, here’s the PHP file that checks the form on the server side:

(processform.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 'Congratulations! The form was submitted successfully.';
    // do something useful with the form data here (send an email confirmation, etc.)
}
else {
    // otherwise display validation errors
    $errors = array_map(function($v){return '<p class="error">' . $v . '</p>';}, $errors);
    echo implode('', $errors);
}
?>

And finally, here’s the JavaScript file that validates the inputted data with jQuery and submits the form via Ajax:

(js/form.js)

$(document).ready(function() {
    $("form").submit(function(event) {
        // validate the 'subject' field
        if ($("#subject").val() == "") {
            $("#errors").html('<p class="error">Enter a subject for your inquiry!</p>');
            $("#subject").focus();
            return false;
        }
        // validate the 'email' field
        if ($("#email").val().indexOf("@") == -1) {
            $("#errors").html('<p class="error">Enter a valid email address!</p>');
            $("#email").focus();
            return false;
        }
        // send the form via Ajax
        event.preventDefault();
        $.ajax({
            type: "POST",
            url: "processform.php",
            data: ({subject: $("#subject").val(), email: $("#email").val(), comments: $("#comments").val()}),
            error: function(msg) {
                $("#errors").html(msg);
            },
            success: function(msg) {
                // display the errors returned by server side validation (if any)
                if (msg.indexOf('Congratulations') == -1) {
                    $("#errors").html(msg);
                }
                // otherwise, display a confirmation message
                else {
                    $("form").html('<h3>' + msg + '</h3>');
                }
            }
        });
    });
});

Mission accomplished. If at this point, you test the script on your own browser and deliberately leave the form’s “email” field blank, (or fill it up with a badly-formatted email address), you should get the following error message:

On the other hand, if you’re nice and complete the form as expected, this is the confirmation message that you should see on screen:

Not too bad, huh? Naturally, there’s plenty of room to improve the script (you can add to it a CAPTCHA, or even perform stricter validation on the server-side). However, in its current state the script demonstrates how easy is to appeal to the jQuery/Ajax/PHP tandem for processing an HTML form, without having to bring accessibility down to its knees.

Final thoughts

Definitively, it’s not breaking news that jQuery makes validating/processing HTML forms via Ajax a breeze, a fact clearly demonstrated by the example developed before. Despite of this advantage, you should always keep in mind that the library is nothing but a JavaScript abstraction framework, and as such, it should be only used for extending (or implementing) the behavior of a web page element, be it a single form control, a div or an entire user interface.

If you’re planning to use jQuery for other purposes (like replacing CSS/(X)HTML, server-side validation without explicitly providing fallback options), I’m afraid that you’re standing in the long line of people who dismiss the real importance of accessibility and safety. So, stick with the structure/presentation/behavior layering model, and your life will be much easier, believe me.

See you in the next web design 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: