Articles

Forms Processing with jQuery, AJAX, and PHP

Introduction

Many of today's cutting-edge Web sites employ the use of AJAX to streamline communication with a remote server without interrupting the user's interaction with the currently loaded page. But incorporating AJAX features into a Web site can be a rather confusing process, particularly because of the need to understand how all of the moving parts go about communicating with one another. In this tutorial I'll show you how to create a form which the user can complete and transparent submit to the server. The server will process the form data and inform the user of the successful submission. To implement this feature we'll use the jQuery JavaScript framework and PHP. We'll tackle the task in three steps, starting by creating the HTML form, then creating the PHP code which will accept and process the form contents, and finally adding the jQuery-specific JavaScript which will connect the form and PHP script together.

Step #1. Create the HTML Form

Creating the form is of course the most trivial task in this project. We'll keep things simple, creating a form which accepts some user feedback regarding the Web site. The rendered form is displayed in Figure 1, followed by the code used to create it.


A User Feedback Form
Click here for larger image

Figure 1. A User Feedback Form (feedback.html)

The HTML code used to create the feedback form follows:

 

  <form id="feedback" method="post" action="feedback.php">
<p>
Your Name:<br />
<input type="text" name="name" size="35" value="" />
</p>
<p>
Your E-mail Address:<br />
<input type="text" name="email" size="35" value="" />
</p>
<p>
Your Feedback:<br />
<textarea name="feedback" rows="5" cols="40"></textarea>
</p>
<p>
<input type="submit" name="submit" value="Send Feedback" />
</p>
</form>

There's really nothing special about this form, although you should take note of the feedback ID assigned to it. This ID will play an important role later in the tutorial.

Step #2. Create the PHP Script

The PHP script (feedback.php) is responsible for processing the user's feedback and returning an appropriate response. In a real-world situation this data would be e- mailed to an administrative contact or inserted into a database, however to keep things simple we'll just insert it into a text file:

  <?php
if ($_POST)
{
$fh = fopen("feedback.txt", "w+");
$name     = $_POST['name'];
$email    = $_POST['email'];
$feedback = $_POST['feedback'];
$success = fwrite($fh, "Name: {$name}, Email: {$email}, Feedback: {$feedback}rn");
fclose($fh);
if ($success) {
echo "Thank you for your feedback!";
} else {
echo "There was a problem processing your feedback.";	
}
}
?>

Notice how we're returning an appropriate message depending upon whether the PHP script was able to successfully write to the text file. Of course, in a real- world situation you'll want to perform the necessary data validation tasks to ensure the user completed all of the required form fields, however in the interests of keeping our eyes on the prize I'll instead opt to keep the PHP script as streamlined as possible.

Step #3. Add the jQuery Code

In this third and final step we'll add the jQuery code to the feedback.html file, wiring the form up to communicate with feedback.php. Let's start by adding the jQuery and jQuery libraries to the feedback.html page.

To improve performance we'll reference the latest jQuery and jQueryUI libraries hosted on Google's content distribution network. Add the following lines to the top of your Web page, specifically somewhere between the <head></head> tags:

  <script type="text/javascript" src="http://www.google.com/jsapi"></script>
<script type="text/javascript">
google.load("jquery", "1.3.2");
google.load("jqueryui", "1.7.2");
</script>

Next you'll want to install the jQuery Form Plugin, which allows you to take advantage of jQuery's powerful selector features to attach AJAX capabilities to any existing form. This plugin also automates many of the other tedious tasks related to forms processing with AJAX, such as whether you'd like the form to be reset after a successful submission, and whether additional tasks should execute following the submission.

To install the jQuery Form Plugin, head over to the plugin's home page, download the file jquery.form.js, and place it somewhere within your Web site. Then, add the following line directly below those you've just added previously:

  <script type="text/javascript" src="/javascript/jquery.form.js"></script>

Next, above the form define the following DIV, which we'll use to provide the PHP script's response back to the user:

  <div id="response"></div>

All that remains now is to create the jQuery code which connects the form to the feedback.php file. Because this is the most involved part of the project I'll present the code and then break it down line-by-line:

 

  01 <script type="text/javascript">
02   google.setOnLoadCallback(function() {
03     $(function() {
04       var options = {      
05         url:       'feedback.php',
06         success:   showResponse,   
07         resetForm: true, 
08         type:      'post'                 
09       }; 
10 
11       // Attach the jQuery form plugin to the form
12       $('#feedback').submit(function(e) { 
13         e.preventDefault();
14         $(this).ajaxSubmit(options);
15       });       
16 
17       // Perform post-submission tasks
18       function showResponse(responseText, statusText)  {
19         $('#response').text(responseText);
20         $('#response').effect("pulsate", {times: 1}, 1000);
21       }
22     });
23   });
24 </script>

Let's review the relevant parts of this code:

 

  • The google.setOnLoadCallback() function referenced on line 02 is a wrapper used to initialize the JavaScript after the page has successfully loaded. This is done in order to ensure that all of the page elements are in place before the JavaScript begins to execute.
  • Lines 04-09 define the options used by the jQuery Form Plugin. The url option defines the URL which we'll be contacting when the form is submitted. The success option defines another JavaScript function which will execute following successful submission of the form data. We'll return to this function in a moment. Setting the resetForm option to true will cause the form fields to be reset to their default values following successful form submission. Finally, the type option tells the jQuery Form Plugin how the form data should be submitted (GET or POST).
  • Lines 12-15 are responsible for listening for the form identified by the DIV ID feedback to be submitted, done by pressing the submit button. When submitted, line 13 will prevent the form's default functionality from occurring (contacting feedback.php using the standard HTTP process), instead using the jQuery form plugin's ajaxSubmit method (line 14) to contact the URL defined by url option.
  • Finally, lines 18-20 define the showResponse function pointed to by the success option. We'll use this method to add a jQuery UI effect to the response DIV in order to draw the user's attention to the PHP script's response.

Believe it or not, this is all of the code you need to begin processing forms using AJAX!

Story by


Website Design | Website Development | Flash animation | Flex applications | Logo Design | Mobile Applications Development | iPhone | iPad | Google Android

Content Management Systems | E-Commerce | Social Networking | Dating Websites | Membership Websites | Zend Framework | PRADO | Symfony | Wordpress

ASP.NET | PHP | C# | Objective-C | AJAX | Web 2.0 | HTML | CSS | Javascript | MySQL | MSSQL

 


Host unlimited domains + get up to 5 FREE domains with your 1&1 hosting account. Must see monthly hosting specials!


Invite your friends to Stable Flow

Enter up to 3 email addresses of your friends: