Using Ajax and jQuery with HTML Forms

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.

In addition, I could not forgive myself if I didn’t mention its Ajax module, one of the library’s most valuable gems, as it can be used for triggering and handling XHR requests, without having to swim in the troubling waters of browser incompatibilities.

Unfortunately, not all is so shiny and pleasant in the jQuery field. Due to the library’s flat learning curve and appealing features that it hides under the hood, it’s common to see a systematic abuse of it (even by highly-renowned web design companies with big pockets), especially when it comes to building dynamic user interfaces and performing form validation.

It seems that for some people, the use of Progressive Enhancement along with jQuery (or any other JavaScript library available out there) is mutually exclusive, something that is a misconception. Fortunately, there’s a bright side to this story: with careful planning, it’s simple to utilize jQuery without having to sacrifice a web site’s accessibility or compromise the level of security of an application.

To give you proof of my claim, I’ll be building a fully-customizable script, which will validate data entered in an HTML form via jQuery’s Ajax module. The data in question will be validated on the server side with PHP as well, regardless of whether or not JavaScript is disabled in the browser.

Getting started: building a sample contact form

Considering that my goal here is to demonstrate how to validate a web form using the jQuery/Ajax/PHP trio, the first step that must be taken is to create the target form. To fit this requirement, below I defined a basic (X)HTML document which includes a simple –yet functional contact form, where users can freely submit their inquiries.

The structure of this sample document looks like this:

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

As you can see, the pertinent contact form contains a few simple fields, which can be used for entering the subject of the inquiry, the user’s email address and finally some comments – nothing overtaxed. In addition, you should notice that the first two fields are required; don’t worry about this for the moment -as I said before, they’ll be validated later on using jQuery/PHP.

With this clean, semantic structure already set, the next thing that must be done is to define the visual presentation of the previous web page and the target form. Well, this will be accomplished with the following CSS file:  

(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;
}

The group of styles defined in the above file are fairly straightforward, so move on and take a look at the image below, which shows how the contact form looks after spicing up its appearance:

That looks quite good, considering that this is only an example. However, this is the boring part, trust me. With the sample contact form already defined and properly styled, it’s time to do something a bit more fun with it. But what? Well, as it was noted in the introduction, it’s necessary to validate the required fields and submit the form via Ajax.

{mospagebreak title=Validating User Data with jQuery, Ajax, and PHP}

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!

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

antalya escort bayan antalya escort bayan Antalya escort diyarbakir escort