Accessible AJAX forms with jQuery

Unless you’ve buried your head in the sand for the last few years, you must have noticed the increased use of Javascript on the web.

One of the most common criticisms levelled against the increased use of Javascript is that it makes accessible web design difficult, or even impossible. This doesn’t have to be the case though – let’s take a look at how progressive enhancement techniques can improve usability without sacrificing accessibility.

The concept is straightforward – make sure that everything works without Javascript, then use Javascript to add the ‘icing on the cake’.

Basically, all the content and functionality on your site should be accessible to your users, regardless of whether Javascript is switched on or off. This not only has benefits for accessibility, but for SEO too.

In this example, I’m going to take a very plain, simple form and add a little bit of magic!

The HTML

<div id="form">
    <form action="" method="post" name="contact-form">
        <label for="name">Your name:</label>
        <input type="text" name="name" id="name" />

        <label for="email">Your email address:</label>
        <input type="text" name="email" id="email" />
        <input type="submit" name="submit" value="submit" />
    </form>
</div>

<div id="results"></div>

The jQuery

$(document).ready(function(){
    $('form[name="contact-form"]').submit(function(event){
        event.preventDefault();

        var myName    = $('input#name').val();
        var myEmail   = $('input#email').val(); 

        $.post('process.php', {name: myName, email: myEmail},
            function(data){
                $('div#results').html(data).fadeOut().fadeIn();
            }
        )
    })
})

Hopefully there’s nothing too scary in the HTML; a couple of input fields and an empty div that will hold our results.

In the javascript, the important parts are lines two and three. Notice that we’re intercepting the form submission, and passing the event as an argument to the following function.

Next, we call event.preventDefault(). This stops events from bubbling up the DOM, in this case, preventing the form from being submitted.

Next, we fire off an AJAX request to process the form. In this case, we’re just echoing out the values that have been entered by the user, but this could be a contact form, a login form, an ‘add to cart’ button – the possibilities are endless!

You can view the demo here.

Note that the form works with or without javascript. Test it yourself by turning javascript off!

I hope this explains the basics of progressive enhancement. For further reading, check out wikipedia’s entry on the subject.

Bookmark and Share

Tags: ,

blog comments powered by Disqus