Publishing System Settings Logout Login Register
AJAX Forms - Create a form with AJAX features that still works without JS!
TutorialCommentsThe AuthorReport Tutorial
Tutorial Avatar
Rating
Add to Favorites
Posted on June 7th, 2007
6673 views
JavaScript
Overview
The conveniences of AJAX

AJAX seems to be an interesting way of using forms and other site features, as it gives the user great convenience, and can just look cool... when used correctly.
The only problem with the choice of using AJAX for major site functions, is you may be blocking some users from using your site. Believe it or not, there are actually people out there who may not have a JavaScript-capable browser, or may just simply have it disabled for one reason or another (security paranoia for example).
To prevent this, in this tutorial I will show you how to plan a form to work not only with AJAX responses, but also function just as well without JavaScript enabled.

For convenience, and because this tutorial is not aimed to actually teach the concept of using AJAX requests, I will be using the ever-so-amazing Prototype framework for my AJAX calls.


Making The Form

First of all, we can construct our form as we normally would.

<form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="post">
<p>Your Name: <input type="text" name="name" /></p>
<input type="submit" name="submit" value="Submit" />
</form>


The line '<?php echo $_SERVER['PHP_SELF']; ?>' simply uses PHP to echo the current page's URI, so the form will send the data to itself.

Now, as you may note, this is just a plain HTML form with nothing special (other than the small bit of PHP in the form's action property).

Next, we will add extra information to the form elements in order for our JavaScript to take advantage of them, and set it up for the AJAX call. We will also add a new div after our form, where our response will be, and add a JavaScript function call for our submit button.

<form id="form" action="<?php echo $_SERVER['PHP_SELF']; ?>" method="post">
<p>Your Name: <input type="text" name="name" id="name" /></p>
<input type="submit" name="submit" id="submit" onclick="sendform();" value="Submit" />
</form>
<div id="response"></div>


Notice, how all we did was simply add an ID attribute to each element that is equivalent to the name, because JavaScript can easily grab the ID, whereas the name will be used in the form's submission by the normal method.

Now, we must think. If we were to try our code now, with JavaScript enabled, it would execute the 'sendform()' function, as stated with the 'onclick' event handler. However, after the 'sendform()' function is done executing, it will still submit the form. To fix this, we simply tell it NO.

<form id="form" action="<?php echo $_SERVER['PHP_SELF']; ?>" method="post" onsubmit="return false;">
<p>Your Name: <input type="text" name="name" id="name" /></p>
<input type="submit" name="submit" id="submit" onclick="sendform();" value="Submit" />
</form>
<div id="response"></div>


All we have done here, is add the 'onsubmit' event handler to the form element itself, and have itself return false. If JavaScript is enabled, this event handler will be activated, and the form will automatically tell itself to stop, and not submit the data. If it were not, then the submit button will work as it normally would!

Next, we will go over the simple AJAX handling.


Writing The JavaScript

Alright, now for the JavaScript behind it all.
This tutorial is not written to teach the fundamentals of using AJAX, or the Prototype framework. I will just be explaining a few of the methods to make it easier to follow the code.

// Send Form Function
function sendform(){
    if($F('name') == ''){
        alert('Please enter your name.');
        $('name').focus();
        return false;
    }
    var opt = {
        method:'post',
        postBody: Form.serialize('form'),
        onLoading: function() { $('submit').disable().value = 'Sending...'; $('response').innerHTML = 'Loading...'; },
        onSuccess: function(t) { $('submit').enable().value = 'Submit'; $('response').innerHTML = t.responseText; },
        }
    new Ajax.Request('ajax.php', opt);
}



First off, our sendform() function will make sure the name input isn't empty. If it is, it will alert the user, place the cursor focus on the form element, and return false, so no request to the AJAX call is made.

With having the Prototype framework, using the method '$F()' grabs the value of a form field. So using '$F('name')' simply grabs the value of the name field.

If the name field does indeed have a value entered, the function will continue to create a new object for the AJAX call. The method is set to 'post', as this will be the method we want to use for our call. For the postBody (a variable that Prototype will use to send the post data), we will use a method built into the Prototype framework called Form.serialize(). This method will return a URI formatted string of all elements of the form given to it. So, for example, our user submits the name 'Michael'. This function will return the string 'name=Michael&submit=Submit'. This will be the body of the post request.

The onLoading function will execute as the call request is made. In this case, we want to keep the user from submitting another request as it is still processing. To do this, we will set the value of the submit button to a convenient loading message, and disable it. We will also set the response div's inner HTML to give a loading message or image (such as the famous loading icon ).

The onSuccess function will execute when the request is complete, passing the new t variable containing the response from the server; in other words, what the script echoes in return to our call. This is automatically sent to the callback from Prototype when it receives the transport from the script. In this case, it will simply undo what our onLoading function did by enabling the submit button, setting its value back to 'Submit', plus adding our response to the response div. The 't.responseText' attribute is how we retrieve the response given to the function by the request.

The final line of the function is what executes all of this. Through the magic of the Prototype framework, the Ajax.Request() method will send a request to the script path provided in the first argument, with the object provided in the second argument.

On the next page, we will build the simple PHP script to give our AJAX call something to return.


PHP AJAX Response

So far, we have the form built. We have the JavaScript ready to send the form and deal with a response from the server. Now all we need to do is create a simple script to deal with the data, and give the AJAX call its response as to how the process went.

This simple script will simply say 'Hello' to the person if the name seems to be a valid name (no special characters), otherwise will say something a little different.

Also, as a simple security measure, I will just make sure our request was made how we set to it be made, and that the full form was correctly submitted. To do this, I will simply make sure the script was called with the correct method, and that the 'submit' field was part of the request. If none of this is correct, we can pretty much assume the page is either being attacked, or the user stumbled upon our AJAX script in some odd fashion they shouldn't have.

No matter what, you should always validate and cleanse through your data, no matter what. Do not trust any kind of user input!

<?php
if($_SERVER['REQUEST_METHOD'] != 'POST' || !isset($_POST['submit']) || $_POST['submit'] != 'Submit')
    exit('Invalid page request!');

if(preg_match('#([A-Za-z' -]*)#i', $_POST['name']))
    $return = '<p><strong>Hello '.$_POST['name'].'!</strong></p>';
else
    $return = '<p><span style="color:#f00;"><strong>Error!</strong></span><br />Your name doesn't seem to look like a normal name. You must be a computer or something, so I can't really say "Hi" since you don't have feelings...</p>';

echo $return;
?>


Now that we've had fun with that, we can continue onto fixing something that's still missing... making this work without JavaScript!


Handling Form Data Without AJAX Call

Now, we are going to have to do something to let our data go to our script even if JavaScript is disabled.
You may see that our form is sent back to the same page as the form, and our AJAX script is on a completely different page. If the page that is being given the data is different from the page that handles the data, how are we going to actually do this?
Simple: we use PHP to include the pages together.

Here we go back to our page with the form, and add some simple code to include our processing page if POST data was sent to it.

<form id="form" action="<?php echo $_SERVER['PHP_SELF']; ?>" method="post" onsubmit="return false;">
<p>Your Name: <input type="text" name="name" id="name" /></p>
<input type="submit" name="submit" id="submit" onclick="sendform();" value="Submit" />
<div id="response">
<?php
if(isset($_POST['submit']))
    include 'ajax.php';
?>
</div>


You'll notice the new PHP code that appears inside of our response div. If the submit button was pressed, and POST data was found, we use the include construct to include our ajax.php file (or whatever you want to call your processing script). Since the processing script acts with our data, and echoes the response, we know that its response will be displayed in the response div correctly.


Final Code

Alright! Now we have a complete functioning form, that works both with and without JavaScript!

Here is the complete code for all three pages involved.

form.php
<form id="form" action="<?php echo $_SERVER['PHP_SELF']; ?>" method="post" onsubmit="return false;">
<p>Your Name: <input type="text" name="name" id="name" /></p>
<input type="submit" name="submit" id="submit" onclick="sendform();" value="Submit" />
<div id="response">
<?php
if(isset($_POST['submit']))
    include 'ajax.php';
?>
</div>


javascript.js
// Send Form Function
function sendform(){
    if($F('name') == ''){
        alert('Please enter your name.');
        $('name').focus();
        return false;
    }
    var opt = {
        method:'post',
        postBody: Form.serialize('form'),
        onLoading: function() { $('submit').disable().value = 'Sending...'; $('response').innerHTML = 'Loading...''; },
        onSuccess: function(t) { $('submit').enable().value = 'Submit'; $('response').innerHTML = t.responseText; },
        }
    new Ajax.Request('ajax.php', opt);
}


ajax.php
<?php
if($_SERVER['REQUEST_METHOD'] != 'POST' || !isset($_POST['submit']) || $_POST['submit'] != 'Submit')
    exit('Invalid page request!');

if(preg_match('#([A-Za-z' -]*)#i', $_POST['name']))
    $return = '<p><strong>Hello '.$_POST['name'].'!</strong></p>';
else
    $return = '<p><span style="color:#f00;"><strong>Error!</strong></span><br />Your name doesn't seem to look like a normal name. You must be a computer or something, so I can't really say "Hi" since you don't have feelings...</p>';

echo $return;
?>



AJAX can be a very powerful and convenient method for user when it comes to dealing with form data, but should not be the only way to submit the form. With this technique, you can ensure your form is sent and properly processed, whether the user chooses to have JavaScript enabled or not.

I hope this tutorial could be of some use to everyone, and that you learned something!
Dig this tutorial?
Thank the author by sending him a few P2L credits!

Send
Demonslay

This author is too busy writing tutorials instead of writing a personal profile!
View Full Profile Add as Friend Send PM
Pixel2Life Home Advanced Search Search Tutorial Index Publish Tutorials Community Forums Web Hosting P2L On Facebook P2L On Twitter P2L Feeds Tutorial Index Publish Tutorials Community Forums Web Hosting P2L On Facebook P2L On Twitter P2L Feeds Pixel2life Homepage Submit a Tutorial Publish a Tutorial Join our Forums P2L Marketplace Advertise on P2L P2L Website Hosting Help and FAQ Topsites Link Exchange P2L RSS Feeds P2L Sitemap Contact Us Privacy Statement Legal P2L Facebook Fanpage Follow us on Twitter P2L Studios Portal P2L Website Hosting Back to Top