-
Featured Columnists
- Faruk Ateş
- Andy Clarke
-
Kris Hadlock
- Designing with Code: Providing Feedback
- Designing With Code: Creating a Resizable Interface
- Designing With Code: CSS Tips and Tricks to Speed Your Workflow
- Designing with Code: Handling PNG Transparency on the Web
- Designing With Code: Collaboration
- Designing With Code: Improving CraigsList
- Designing With Code: How to Create a Tag Cloud
- Designing with Code: RSS
- Designing With Code: Tumblelogging
- Designing With Code: Create a DropIn JavaScript Component
- Designing with Code: Leveraging Your Existing Content
- Designing With Code: Leveraging RSS
- Designing With Code: Converting Forms to Ajax
- Designing with Code: Converting Forms to Ajax, Part 2
- Designing With Code: Monster Mash
- How to Create Dynamic Script Tags for Ajax Components
- Creating a Winning Proposal for Web Projects
- Creating a Web Design Questionnaire
- Using Stylesheets in Flash CS3
- Animating with XML in Flash CS3
- Creating a Full-Screen Web Site with Flash CS3
- Robert Hoekman, Jr.
- Molly Holzschlag
- Sarah Horton
- Miraz Jordan
- Jonathan and Lisa Price
- Catherine Seda
- Dave Shea
- Dave Taylor
-
Table of Contents
- Welcome
- Web Basics
- Publishing on the Web: Putting Files on the Server
- Web Design Process and Workflow
- Project Management
- Mark My WWWord: HTML and XHTML
- Standards Compliance
- Layouts
- Forms
- Meta Tags and Search
- Usability
- Accessibility
- Enhancing Web Page Interaction
- Web Graphics
- Web Page Optimization
- Multimedia
- Content
- Overview of Servers
- Server Programming Basics
- Careers in Web Design
- Tools
- Tutorials
- Intellectual Property for Web Designers
Designing with Code: Converting Forms to Ajax, Part 2
Last updated Oct 17, 2003.
In the last Designing with Code article, Converting Forms to Ajax, I showed you how to convert your standard web forms to Ajax by including a simple JavaScript object. In this article, I'll show you how to handle the request on the server-side and then the response on the client-side.
The example project in this article can be downloaded here and viewed live here. We will learn how to create a login form, reroute the response through Ajax using the same technique learned in the previous article, handle the request on the server, return a response based on database values that were selected, and finally parse the data on the client side when the response is received. Although it's not required, this article assumes that you have a basic understanding of JavaScript, PHP, and XML.
Adding a Database Table
The first thing we need to do is create a database table that contains the information with which our application will interact. The table contains a few user values to provide an example of how a user would login through our Ajax form and how we would gather their information based on the request. Use the code from Listing 1 to create the table and populate it with myself as a user.
Listing 1: Creating a user database table (informit_ajaxform.sql)
CREATE TABLE informit_ajaxform ( id int(11) unsigned NOT NULL auto_increment, username varchar(25) NOT NULL default ’’, password varchar(50) NOT NULL default ’’, firstName varchar(25) NOT NULL default ’’, lastName varchar(50) NOT NULL default ’’, company varchar(50) NOT NULL default ’’, PRIMARY KEY (id) ) ENGINE=MyISAM; insert into informit_ajaxform values(’1’,’kris’,’hadlock’,’Kris’,’Hadlock’,’Studio Sedition’);
This sql code will create a database table named informit_ajaxform with an id, username, password, firstName, lastName and company. These fields will be populated with an id of "1", username of "kris", password of "hadlock", firstName of "Kris", lastName of "Hadlock" and a company name of "Studio Sedition". Any users can be added to this form, I simply added myself as an example.
Creating a Login Form
The first file that needs to be created is an index page to contain the login form (Listing 2). This form will post the same way that we posted forms in the previous article, just with different data. This data will be used to gather user information from a database based on the username and password that are passed. These values will be provided by the user and gathered by our PostManager JavaScript object upon submission. The values are retrieved by iterating through the fields in the form, determining what type of field each one is and then using the appropriate code to access its value.
Listing 2: The login form (index.html)
<html> <head> <title>Ajax Form</title> <script type="text/javascript" src="js/Ajax.js"></script> <script type="text/javascript" src="js/PostManager.js"></script> </head> <body> <form action="posthandler.php" method="post" onsubmit="PostManager.Send(this); return false;"> Username:<br/><input type="text" name="username" /> <br/><br/> Password:<br/><input type="text" name="password" /> <br/><br/> <input type="submit" value="submit" /> </form> </body> </html>
Once the form has been posted, we will need to have a file on the server to handle the request and return an appropriate response. Let's take a look at how to accomplish this.
Handling the Request on the Server
In order to handle the request and deliver a response, we need to create a simple php file. This file will be called posthandler.php (Listing 3), as it was in the previous article, although this file is very different. First of all, it includes an object called PostHandler, which will access the database table that we created in the first section of this article. Second, it returns a response to the client, which the other file did not.
Listing 3: Handling form posts (posthandler.php)
<?php
header("Content-Type: application/xml; charset=ISO-8859-1");
echo ’<?xml version="1.0" encoding="ISO-8859-1" ?>’;
echo ’<response>’;
if($_POST) $request = $_POST;
else if($_GET) $request = $_GET;
else
{
echo ’<error>no query</error>’;
$request = array();
}
$ph = new PostHandler();
echo $ph->Login($request);
echo ’</response>’;
?>
<?php
class PostHandler
{
private $dbhost = ’host name’;
private $dbusername = ’username’;
private $dbpassword = ’password’;
private $dbname = ’database name’;
private $dblink;
public function PostHandler()
{
$this->dblink = mysql_connect($this->dbhost, $this->dbusername, $this->dbpassword);
}
public function Login($request)
{
mysql_select_db($this->dbname);
$query = "SELECT * FROM informit_ajaxform WHERE ";
$index = 0;
foreach($request as $key => $value)
{
if($key == ’username’ || $key == ’password’)
{
if($index > 0) $query .= " AND ";
$query .= $key ."=’". $value ."’";
$index++;
}
}
$result = mysql_query($query, $this->dblink);
$user = mysql_fetch_object($result);
$xml = ’’;
foreach($user as $property => $value)
{
$xml .= ’<’. $property .’>’. $value .’</’. $property .’>’;
}
return $xml;
}
}
?>
This file can contain a number of ways to access the database and return a response; for this example, I choose one that allows us to gather the user data based on the username and password that were passed through the request. If a user exists based on these credentials, we will return an xml file that has node names that are equal to the user properties and their corresponding values as the node value. This way, on the client side we'll know what property and value go together by simply reading the node name and its corresponding node value.
Handling the Response
Once our PostManager JavaScript object receives the response from the server we can handle the data however we like. For the purposes of this article, I'm simply writing the data to the page with the property name followed by its value.
Listing 4: Handling the request and response on the client-side (PostManager.js)
var PostManager = new Object();
PostManager.Send = function(form)
{
PostManager.currentForm = form;
var query = PostManager.buildQuery(form);
Ajax.Request(form.method, form.action, query, PostManager.OnResponse);
}
PostManager.OnResponse = function(xml)
{
PostManager.currentForm.style.display = ’none’;
var elements = xml.childNodes;
for(var i=0; i<elements.length; i++)
{
document.getElementsByTagName(’body’)[0].innerHTML += elements[i].nodeName +": "+ elements[i].firstChild.data +"<br/>";
}
}
PostManager.buildQuery = function(form)
{
var query = "";
for(var i=0; i<form.elements.length; i++)
{
var key = form.elements[i].name;
var value = PostManager.getElementValue(form.elements[i]);
if(key && value)
{
query += key +"="+ value +"&";
}
}
return query;
}
PostManager.getElementValue = function(formElement)
{
if(formElement.length != null) var type = formElement[0].type;
if((typeof(type) == ’undefined’) || (type == 0)) var type = formElement.type;
switch(type)
{
case ’undefined’: return;
case ’radio’:
for(var x=0; x < formElement.length; x++)
if(formElement[x].checked == true)
return formElement[x].value;
case ’select-multiple’:
var myArray = new Array();
for(var x=0; x < formElement.length; x++)
if(formElement[x].selected == true)
myArray[myArray.length] = formElement[x].value;
return myArray;
case ’checkbox’: return formElement.checked;
default: return formElement.value;
}
}
The only difference between this file and the one from the previous article is that we are handling a response from the server and tracking the current form in the Send method so that we can later access it in the object's other methods. If you added me as a user in your database, you can now simply enter "kris" as the username and "hadlock" as the password in order to see it in action.
