Digital Flow Software dhtml popup window

Advanced DHTML Popup Technology made easy, fast and customizable  

Advanced DHTML Popup
DHTML Popup windows made easy

DHTML & AJAX in Content Management

2. Simple AJAX form validation

Let's take a look at an elementary example of AJAX employed from within a DHTML popup. It contains an email sign-up form. The example shows a simplistic validation of name and email, using a small PHP script which just checks a couple of things. The purpose is just to see the advantage of using AJAX here, and that it is possible when combined with a DHTML layer.

By doing this we combine the security of server-side processing with the advantages of same-page error notification common to standard client-side JavaScript form validation techniques. Added to this is the unique advantage of AJAX that allows immediate updating of just a part of the content without having to reload the page.


The demo:

Show the email sign-up form


If you click the link above you will see a normal DHTML popup containing a form slide-in. It will automatically position itself on the lower edge of the browser in the center, and will stay there when the browser is moved or the window is scrolled.

If a single character is typed into the name field a warning will very shortly appear just under that the name is too short.

Note that it is not necessary to press 'submit' for the validation to happen, this is all in real time. If 3 or more characters are typed, the name is reported as valid, unless it happens to be in a list of reserved names; one of which is 'joe', in which case a different warning is issued.

Note that these messages are being written into a part of the content without the need to refresh the whole page. If now an email is entered, several checks will ensure that it has all the right parts to it, including an '@' and at least a 2 digit domain etc. Again, a message is written to the content indicating a valid email or otherwise.


The code:


The code comes in two parts, the content of the popup, and the PHP on the server. Below is the content of the popup, which in this case is stored in an iFrame and referenced by the content string of the popup.

There are two functions in the script part of the page below, userValidate() is called after a character is typed into the user field of the form, and emailValidate() after typing in the email field.

In either case a PHP script (below) is called asynchronously - i.e. the third argument of the 'open' method is 'true', meaning that the script will continue to execute without waiting for the server response. It is called with the argument 'name' or 'email' set to the key that was pressed in either field.

Each of these functions contains a function to detect completeness of the request, and to then update a div in the content with the response returned from the PHP function called on the server.

The HTML part of the page sets up the form and the event handler 'onkeyup'. This is everything seen in the popup itself. Below we look at the server-side script called by this page.

<html>
<head></head>
<body STYLE="background-color:transparent">
<script type="text/javascript">
var http = false;

if(navigator.appName == "Microsoft Internet Explorer") {
  http = new ActiveXObject("Microsoft.XMLHTTP");
} else {
  http = new XMLHttpRequest();
}

function userValidate(user) {
  http.abort();
  http.open("GET", "signup1.php?name=" + user, true);
  http.onreadystatechange=function() {
    if(http.readyState == 4) {
      document.getElementById('userdiv').innerHTML = http.responseText;
    }
  }
  http.send(null);
}
function emailValidate(email) {
  http.abort();
  http.open("GET", "signup1.php?email=" + email, true);
  http.onreadystatechange=function() {
    if(http.readyState == 4) {
      document.getElementById('emaildiv').innerHTML = http.responseText;
    }
  }
  http.send(null);
}
</script>


<center>
<h3>Sign up for our newsletter</h3>
<form name="form1" method="post" action="mailto:info@dpopup.com" >
<table border=0>

<tr>
<td style="font-size:12"><strong>Name:</strong></td>
<td><input onkeyup="userValidate(this.value)" name="name" type="text" id="name" size="30"></td>
</tr>
<tr>
<td></td>
<td><div style="height:20px" id="userdiv"> </div></td>
</tr>

<tr>
<td style="font-size:12"><strong>Email:</strong></td>
<td><input onkeyup="emailValidate(this.value)" name="email" type="text" id="email" size="30"></td>
</tr>
<tr>
<td></td>
<td><div style="height:20px" id="emaildiv"> </div></td>
</tr>

<tr align="right" ><td></td>
<td>
<input type="submit" name="Submit" value="Submit">
<input type="reset" name="reset" value="Reset"></td></tr>
</table>
</form>
</center>

<p align='center' style="font-size:11;color: ff0000"> We will never sell, rent or exchange your email with anyone

<a href="javascript:void(0)" style="font-size:10;color: 0000ff;">Privacy Policy</a></p>

</body>
</html>



Below is the PHP script 'signup1.php' on the server. At the end a decision based on the variable passed by the URL is made, to call the appropriate function.

The function nameVal(), after declaring an array containing some reserved names, checks if the string is null and returns if it is. If not, it checks if the number of characters so far in the name field is less than 3, and if so returns the first warning. If not, it goes on to check against the reserved names and if a match is found returns the second warning. Finally if both these tests are passed it returns with 'Valid name'.

The function emailVal() uses a regular expression to determine (a) that at least the 3 main parts are present, including the '@' and a domain of 2-3 characters only.

<?php

function nameVal($name) {
  $names=array(john,joe,jim);
  $count = count($names);

  if($name == '') {
    return '';
  }

  if(strlen($name) < 3) {
    return "<span id=\"warn\">Name must be 3 chars or more</span>\n";
  }

  for ($i = 0; $i < $count; $i++) {
    if($name == $names[$i]){
      return "<span id=\"warn\">Please choose another name</span>\n";
    }
  }
  
  return "<span id=\"notice\">Valid name</span>\n";
}

function emailVal($email) {
  if($email == '') {
    return '';
  }

  if(eregi("^[_a-z0-9-]+(\.[_a-z0-9-]+)*@[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,3})$", $email)){
    return "<span id=\"notice\">Valid email</span>\n";
  }else{
    return "<span id=\"notice\">Invalid email</span>\n";
  }  
}

if($_REQUEST['name']){
  echo nameVal(trim($_REQUEST['name']));
}else{
  echo emailVal(trim($_REQUEST['email']));
}

?>


The conclusion:

Remember that this is not a real-world example, it is simply meant to illustrate the idea of asynchronous communication with the server to perform real-time validation checks that (a) allow processing to occur without leaving the page or refreshing it and (b) allow the processing to happen on the server rather than rely on client-side JavaScript.

In a more realistic situation the processing would not happen at each key stroke for example, but on submission instead. Also of course the validation would be thorough, here it is simplistic to make the point.


Article Index  


Jim Cantrell - Freebits

"I would like to thank you for creating a product that allows me to target specific pages on my site whilst not annoying my visitors. Advanced DHTML Popup is easy to use and the options are endless, plus your excellent support which helped me to create something different make this money well spent. I can only wait to see what new templates will appear in future upgrades. Thank you Digital Flow Software." Freebits
[Graded transparency slide-in popup for redirection]

User Sites & Testimonials


Supports all standard methods of page entry, automatic or manual triggering, scripting capabilities for extensions


Wide range of customization options, including the ability to overlay any chosen image including transparencies


Use with server-side script (ASP, PHP etc.) and databases (e.g. MySQL) for dynamic variable substitution, content, links etc


Create and embed multiple popups in a single page to appear either sequentially or simultaneously


Range of templates supplied, some of which contain special additional script functions

 Registered Copyright

Copyright & Legal  |   This Web Site and all contents are Copyright © 2005-2008 by Digital Flow Software. All Rights Reserved