AJAX & Prototype Page 3 - PHP AJAX Form Validation |
Let us make an actual web application. For example, if you are making a web form that can accept the following fields:
We will need this form to be powered by AJAX so that, when the form is submitted to the server, there will be no refresh or page reload. The first thing we need to do is let PHP start a session which will be needed to pass captcha answers from the original captcha generator PHP file (like captcha.php) <?php session_start(); ?> In this article, we will use the prototype AJAX, so we need to append in the <head> tag the JavaScript files needed for AJAX: <script type="text/javascript" src="prototype.js"></script> Discussion of the prototype.js is out of the scope of this article. You can read some good references relating to this application. The next thing we need is the actual web form. <form action="ajaxvalidate.php" method="post" onsubmit="return false;"> Enter your Full Name, First name and Last name ONLY (Example: John Doe)<br /> <input style="background-color: #FFFFC0" type="text" name="name" id="name" size="50"> <br /><br /> Enter your Phone number (numbers only, no dashes and spaces)<br /> <input style="background-color: #FFFFC0" type="text" name="phonenumber" id="phonenumber" size="35"> <br /><br /> Enter your Age (Numbers only)<br /> <input style="background-color: #FFFFC0" type="text" name="age" id="age" size="50"> <br /><br /> <img src="captcha.php" /> <br /> Enter the Captcha as shown above: <br /> <br /> <input style="background-color: #FFFFC0" type="text" name="captcha" id="captcha" size="10"> <br /> <br /> <input type="submit" value="Submit" onClick="sendRequest()"> </form> The ajaxvalidate.php is the actual PHP script that will process the form inputs. JavaScript executes the sendRequest() function after the user clicks the submit button. The code of this JavaScript function is: <script type="text/javascript"> function sendRequest() { new Ajax.Request("ajaxvalidate.php", { method: 'post', parameters: 'name='+$F('name')+'&phonenumber='+$F('phonenumber')+'&age='+$F('age')+'&captcha='+$F('captcha'), onComplete: showResponse }); } function showResponse(req){ $('show').innerHTML= req.responseText; } </script> As you can see, there are four variables to be submitted to the PHP script (name, phone number, age and the user captcha input). The PHP output will then be shown via the showResponse(req)JavaScript function. Any HTML output will be shown with an ID identified as "show" (see show response function code above). In the web form, this is the actual code: <p class="yellow" id="show"></p> The HTML output from PHP will have a background of yellow defined by this style: <style type="text/css"> P.yellow {background-color: #ffff00;} </style>
blog comments powered by Disqus |
|
|
|
|
|
|
|