At the Forge - JavaScript, Forms and Ajax
Listing 3. js-register.html
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head><title>Register</title>
<script type="text/javascript">
<!--
var usernames = ['abc', 'def'];
function removeText(node) {
if (node != null)
{
if (node.childNodes)
{
for (var i=0 ; i < node.childNodes.length ; i++)
{
var oldTextNode = node.childNodes[i];
if (oldTextNode.nodeValue != null)
{
node.removeChild(oldTextNode);
}
}
}
}
}
function appendText(node, text) {
var newTextNode = document.createTextNode(text);
node.appendChild(newTextNode);
}
function setText(node, text) {
removeText(node);
appendText(node, text);
}
function checkUsername() {
var new_username = document.forms[0].username.value;
var found = false;
var warning = document.getElementById("warning");
var submit_button = document.getElementById("submit-button");
// Is this new username already taken? Iterate over
// the list of usernames to be sure.
for (i=0 ; i<usernames.length; i++)
{
if (usernames[i] == new_username)
{
found = true;
}
}
// If we find the username, issue a warning and stop
// the user from submitting the form.
if (found)
{
setText(warning, "Warning: username '" + new_username
+"' was taken!");
submit_button.disabled = true;
}
else
{
removeText(warning);
submit_button.disabled = false;
}
}
--> </script>
</head>
<body>
<h2>Register</h2>
<p id="warning"></p>
<form action="/cgi-bin/register.pl" method="post">
<p>Username: <input type="text" name="username"
onchange="checkUsername()" /></p>
<p>Password: <input type="password" name="password" /></p>
<p>E-mail address: <input type="text" name="email_address" /></p>
<p><input type="submit" value="Register" id="submit-button"
/></p>
</form>
</body>
</html>
This is the way that most client-side Web programs are structured. JavaScript functions do the actual work, but they are invoked by event handlers defined in the HTML. So, in Listing 3, we see:
<p>Username: <input type="text" name="username"
onchange="checkUsername()" /></p>
This tells the browser that when the username text field changes, it should invoke the checkUsername() function. When this function is executed, it begins with the following:
var new_username = document.forms[0].username.value;
The new_username variable gets the value of the username text field. We do this by starting off with the document object (representing our HTML document), then taking the first element of its forms array (representing the first, and only, form in the document). The username property of the form gives us the node for the username text field, whose value we can then retrieve (as a string) with the value property.
Traversing the tree in this way is typical when working with JavaScript. However, it is also possible to jump immediately to a particular form element, assuming that element has been assigned an id attribute. IDs must be unique within a document, meaning that we can find a node with the appropriate method:
var warning = document.getElementById("warning");
var submit_button = document.getElementById("submit-button");
Each of the above two lines uses document.getElementById to retrieve a node from the document tree, identified with an id attribute. (If nothing matches, the variable is set to the null value.)
The list of user names has been hard-coded in Listing 3, which is something you would never try in an actual application. I discuss this further below, and we will find production-quality, Ajax-style solutions next month.
Now that we have a list of user names in JavaScript, we want to force the user to choose a user name that does not clash with one already in use. We will do this by checking the proposed user name against the list that we have already collected. If the user name is already taken, we will warn the user by modifying the HTML of the current page and then by disabling the submit button. Only when the chosen user name is new and unique will the user be allowed to submit it to the server. This doesn't mean we will remove our uniqueness checks on the server or in the database, but it offloads some of that checking to the client and makes the application more immediately responsive to the user's needs.
We do this by iterating over usernames, the array containing user names:
for (i=0 ; i<usernames.length; i++)
{
if (usernames[i] == new_username)
{
found = true;
}
}
If we find a match between the user's requested new user name and one in the array, then we set the found variable to be true. Otherwise, it continues to be set to false. This then tells us whether we need to warn the user about a conflict and disable the submit button or vice versa.
Warning the user consists of two steps. The first involves setting the warning text—that is, the text inside of the <p> tags above the form—to an appropriate message. We already set the variable warning to point to that node at the beginning of the checkUsername function, which means that we now must eliminate all children of the warning node. Actually, we don't want to eliminate all children, but merely the ones with a nodeValue property, because that is where text is stored. The removeText function does that by iterating over each of a node's children, checking to see if it contains text and removing it if it does:
if (node.childNodes)
{
for (var i=0 ; i < node.childNodes.length ; i++)
{
var oldTextNode = node.childNodes[i];
if (oldTextNode.nodeValue != null)
{
node.removeChild(oldTextNode);
}
}
}
Once we have removed text children from the warning node, we then can add a new text child to the warning node, containing the message we want to display. This is done in the appendText function:
function appendText(node, text) {
var newTextNode = document.createTextNode(text);
node.appendChild(newTextNode);
}
As of this point, the user has received a warning about the chosen user name, indicating that it will not be accepted because the user name was already taken. However, we cannot rely on users to read and follow the instructions in a warning message. Rather, we should disable the form's submit button, making it difficult for users even to send the bad user name to our server-side program. We can do this by setting the submit button's disabled property:
submit_button.disabled = true;
To recap—when the user enters a value in the username text field that is in the usernames array, we remove any existing text children from the warning node. We then add a new text child node to warning, indicating that the chosen user name already has been taken. Finally, we disable the submit button in the HTML form.
Of course, we want the user to submit the form eventually, but only after entering a user name not in the usernames array. This means we must remove text children from the warning node, and then re-enable the submit button:
removeText(warning); submit_button.disabled = false;
Sure enough, this combination of JavaScript functions seems to do the trick. User names that are not in the usernames array remove any error messages and re-activate the form, allowing us to submit it to the server-side CGI program and register with the site. User names that are in the array, however, produce a warning and stop us from being able to submit the form. It's not Ajax just yet, but it is more responsive to the user than our pure server-side solution.
Realizing the promise of Apache® Hadoop® requires the effective deployment of compute, memory, storage and networking to achieve optimal results. With its flexibility and multitude of options, it is easy to over or under provision the server infrastructure, resulting in poor performance and high TCO. Join us for an in depth, technical discussion with industry experts from leading Hadoop and server companies who will provide insights into the key considerations for designing and deploying an optimal Hadoop cluster.
Sponsored by AMD
Built-in forensics, incident response, and security with Red Hat Enterprise Linux 6
Every security policy provides guidance and requirements for ensuring adequate protection of information and data, as well as high-level technical and administrative security requirements for a system in a given environment. Traditionally, providing security for a system focuses on the confidentiality of the information on it. However, protecting the data integrity and system and data availability is just as important. For example, when processing United States intelligence information, there are three attributes that require protection: confidentiality, integrity, and availability.
Learn more about catching the bad guy in this free white paper.
Sponsored by DLT Solutions
| Designing Electronics with Linux | May 22, 2013 |
| Dynamic DNS—an Object Lesson in Problem Solving | May 21, 2013 |
| Using Salt Stack and Vagrant for Drupal Development | May 20, 2013 |
| Making Linux and Android Get Along (It's Not as Hard as It Sounds) | May 16, 2013 |
| Drupal Is a Framework: Why Everyone Needs to Understand This | May 15, 2013 |
| Home, My Backup Data Center | May 13, 2013 |
- seo services in india
1 hour 39 min ago - For KDE install kio-mtp
1 hour 40 min ago - Evernote is much more...
3 hours 40 min ago - Reply to comment | Linux Journal
12 hours 25 min ago - Dynamic DNS
12 hours 59 min ago - Reply to comment | Linux Journal
13 hours 58 min ago - Reply to comment | Linux Journal
14 hours 48 min ago - Not free anymore
18 hours 50 min ago - Great
22 hours 37 min ago - Reply to comment | Linux Journal
22 hours 45 min ago
Enter to Win an Adafruit Pi Cobbler Breakout Kit for Raspberry Pi

It's Raspberry Pi month at Linux Journal. Each week in May, Adafruit will be giving away a Pi-related prize to a lucky, randomly drawn LJ reader. Winners will be announced weekly.
Fill out the fields below to enter to win this week's prize-- a Pi Cobbler Breakout Kit for Raspberry Pi.
Congratulations to our winners so far:
- 5-8-13, Pi Starter Pack: Jack Davis
- 5-15-13, Pi Model B 512MB RAM: Patrick Dunn
- 5-21-13, Prototyping Pi Plate Kit: Philip Kirby
- Next winner announced on 5-27-13!
Featured Jobs
| Linux Systems Administrator | Houston and Austin, Texas | Host Gator |
| Senior Perl Developer | Austin, Texas | Host Gator |
| Technical Support Rep | Houston and Austin, Texas | Host Gator |
| UX Designer | Austin, Texas | Host Gator |
| Web & UI Developer (JavaScript & j Query) | Austin, Texas | Host Gator |
Free Webinar: Hadoop
How to Build an Optimal Hadoop Cluster to Store and Maintain Unlimited Amounts of Data Using Microservers
Realizing the promise of Apache® Hadoop® requires the effective deployment of compute, memory, storage and networking to achieve optimal results. With its flexibility and multitude of options, it is easy to over or under provision the server infrastructure, resulting in poor performance and high TCO. Join us for an in depth, technical discussion with industry experts from leading Hadoop and server companies who will provide insights into the key considerations for designing and deploying an optimal Hadoop cluster.
Some of key questions to be discussed are:
- What is the “typical” Hadoop cluster and what should be installed on the different machine types?
- Why should you consider the typical workload patterns when making your hardware decisions?
- Are all microservers created equal for Hadoop deployments?
- How do I plan for expansion if I require more compute, memory, storage or networking?




Comments
is that can do for mysql and for long title of artiles
HI
this is very good post
but i wonder you can help for the one wwork with mysql and
special in case of record have long title
eg: when some one posting articles the Ajax will check for its title ( may be long ) and find in data, is some realy similar articles exiting with that title .. so poster do not make double post ..
if have any solution please pm mail me yahoo binhaus
thanks
kind regards