473,387 Members | 1,549 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,387 software developers and data experts.

ajax form validation

hi, i want to use ajax to validate a form. here is my work including 2 files, main.html and process.php

main.html
[html]
<script language="javascript">
//initialize xmlhttprequest object...
var request=false;
try
{
request=new XMLHttpRequest();//for FF & IE 7
}
catch(e)
{
try
{
request=new ActiveXObject('Msxml2.XMLHTTP'); //for IE5+
}
catch(e)
{
try
{
request=new ActiveXObject('Microsoft.XMLHTTP');//for IE5
}
catch(e)
{
request=false;
alert('AJAX not supported');
}
}
}

function execute()
{
if(request.readyState==4 && request.status==200)
{
document.getElementById('errorname').innerHTML=req uest.responseText;
}
}

function validate(value,id)
{
srv="process.php?"+value
request.open('GET',srv)
request.onreadystatechange= function()
{
if(request.readyState==4 && request.status==200)
{
document.getElementById(id).innerHTML=request.resp onseText;
}
}
request.send(null)
}
</script>

<table width="500">
<tr>
<td>Username:</td>
<td><input type="text" name="username" autocomplete="off" onchange="validate('name='+this.value,'errorname') " /></td>
</tr>
<tr><td colspan="2"><div id="errorname"></div></td></tr>

<tr>
<td>Email:</td>
<td><input type="text" name="email" autocomplete="off" onchange="validate('email='+this.value,'erroremail ')" /></td>
</tr>
<tr><td colspan="2"><div id="erroremail"></div></td></tr>

<tr>
<td>Phone:</td>
<td><input type="text" name="phone" autocomplete="off" onchange="validate('phone='+this.value,'errorphone ')" /></td>
</tr>
<tr><td colspan="2"><div id="errorphone"></div></td></tr>

<tr>
<td>Address:</td>
<td><input type="text" name="address" autocomplete="off" onchange="validate('address='+this.value,'erroradd ress')" /></td>
</tr>
<tr><td colspan="2"><div id="erroraddress"></div></td></tr>

<tr>
<td>&nbsp;</td>
<td><input type="submit" name="submit" onclick="validate('submit=ok','errorsubmit')" value="Submit" /></td>
</tr>
<tr><td colspan="2"><div id="errorsubmit"></div></td></tr>
</table>
</body>
</html>
[/html]

process.php
[php]
<?php
include('db.php');

function valid_name($str)
{
return ( ! preg_match("/^([-a-z0-9])+$/i", $str)) ? FALSE : TRUE;
}

function valid_phone($str)
{
return ( ! preg_match("/^([0-9])+$/i", $str)) ? FALSE : TRUE;
}

function valid_email($str)
{
return ( ! preg_match("/^([a-z0-9\+_\-]+)(\.[a-z0-9\+_\-]+)*@([a-z0-9\-]+\.)+[a-z]{2,6}$/ix", $str)) ? FALSE : TRUE;
}

if($_GET['name'])
{
$name=$_GET['name'];
$q1=mysql_query("SELECT username FROM users WHERE username = '$name'") or die(mysql_error());

if(valid_name($name)==FALSE) die('<font color=red>Invalid username</font>');

if($name==''|| strlen($name)<3) die('<font color=red>Username must be at least 3 characters</font>');

if(mysql_num_rows($q1)!=0) die ('<font color=red>Name is in use');

else
{
echo $nameok=1;
echo '<font color=blue>Name OK!</font>';
}
}

if($_GET['email'])
{
$email=$_GET['email'];

if(($email=='')||(valid_email($email)==FALSE)) die("<font color=red>Invalid Email Address!</font>");

else
{
echo '<font color=blue>Email OK</font>';
echo $emailok=1;
}
}

if($_GET['phone'])
{
$phone=$_GET['phone'];

if(($phone=='')|| (valid_phone($phone)==FALSE)) die("<font color=red>Invalid phone number!</font>");

else
{
echo '<font color=blue>Phone OK</font>';
echo $phoneok=1;
}
}

if($_GET['address'])
{
$address=$_GET['address'];

if($address=='') die("<font color=red>Address has not been filled in!</font>");

else
{
echo '<font color=blue>Address OK!</font>';
echo $addressok=1;
}
}

if($_GET['submit'])
{
echo $emailok;
echo $addressok;
echo $phoneok;
echo $nameok;

if(($nameok==1)&&($addressok==1)&&($phoneok==1)&&( $emailok==1))
{
echo 'you are done!';
}
die('Ouch!');

}

?>
[/php]

each time user input satisfies the given condition I mark it with value 1 ($nameok=1, for example). at the very final step of the work when submitting, however, all the marks assigned seem to get back to 0 (as function echo gives me nothing)

anyone can show me what's wrong here?
Apr 3 '08 #1
5 1512
hsriat
1,654 Expert 1GB
There may be some other errors too, but to start with, do this change...

Expand|Select|Wrap|Line Numbers
  1. validate('address='+escape(this.value),'erroraddress')
Similarly in other fields.


PS: No space before ss
Apr 3 '08 #2
There may be some other errors too, but to start with, do this change...

Expand|Select|Wrap|Line Numbers
  1. validate('address='+escape(this.value),'erroraddress')
Similarly in other fields.


PS: No space before ss
thanks, but it does not work. i don't think that validate function has anything wrong. things go well until the submitting step

[php]
if($_GET['submit'])
{
echo $emailok;
echo $addressok;
echo $phoneok;
echo $nameok;

if(($nameok==1)&&($addressok==1)&&($phoneok==1)&&( $emailok==1))
{
echo 'you are done!';
}
die('Ouch!');


}
[/php]

i don't know why either all the assigned marks ($emailok, $addressok, $phoneok, $nameok) get back 0 righ after quiting each of the previous individual if or somehow they're all reassigned 0 right before the final step starts thus the final if would never be satisfied (each cannot be 1). whether previous steps are passed or not, the final message would always be 'Ouch', not the expected 'you are done!'. how can i make this stupid stuff work, omg =.=


anyway, is there any other way working?the submit process should only work if all the conditions on name, email phone and address are satisfied (disable the submit button if they are not, for example)
Apr 4 '08 #3
hsriat
1,654 Expert 1GB
When once you run the validation by running the process.php, it sets the variable to one. But you want that variable to remain 1 when you next time execute that script.
That's not possible. Once you run a script, at the end of the script, all the variables are washed from the memory.

So in order to keep a track of the validated values, do the following changes.
In process.php[php]//remove LINE 32, 33 and similar for email etc
echo $nameok=1;
echo '<font color=blue>Name OK!</font>';
//and replace them with
echo "1|<font color=blue>Name OK!</font>";
//and similarly in all other validations[/php]

In you main.htm
Expand|Select|Wrap|Line Numbers
  1. //declare 2 global variables
  2. //all the IDs
  3. var ids = new Array('errorname', 'erroremail', 'errorphone', 'erroraddress');
  4. var isValid = new array();
  5. for (var i=0; i<ids.length; i++)
  6. isValid[ids[i]] == flase;
  7. //declare all of them as false
  8.  
  9. //on line number 44
  10. //remove
  11.     document.getElementById(id).innerHTML=request.responseText;
  12. //replace it with
  13.     resp = request.responseText.split('|');
  14.     if (resp[0] == '1') {
  15.         isValid[id] = true;
  16.         document.getElementById(id).innerHTML = resp[1];
  17.     }
  18.     else {
  19.         document.getElementById(id).innerHTML=request.responseText;
  20.     }
  21. //----
  22.  
  23. //make a function
  24. function validateAll() {
  25.     for (var i=0; i<ids.length; i++)
  26.     if (!isValid[ids[i]]) {
  27.         //add any error message here
  28.         return false;
  29.     }
  30.     return true;
  31. }
  32. //on the onclick event of the submit button, call validateAll() function instead of validate funtion

Hope this will work.


Harpreet
Apr 4 '08 #4
I nearly forgot this problem and it's just minutes ago i tried your suggestion with a bit modification and I think it works now. thanks alot. here is my work:

validate.js
Expand|Select|Wrap|Line Numbers
  1. //initialize xmlhttprequest object...
  2. var request=false;
  3. try
  4. {
  5.     request=new XMLHttpRequest();//for FF & IE 7    
  6. }    
  7. catch(e)
  8. {
  9.     try
  10.     {
  11.         request=new ActiveXObject('Msxml2.XMLHTTP'); //for IE5+
  12.     }
  13.     catch(e)
  14.     {
  15.         try
  16.         {
  17.             request=new ActiveXObject('Microsoft.XMLHTTP');//for IE5
  18.         }
  19.         catch(e)
  20.         {
  21.             request=false;
  22.             alert('AJAX not supported');            
  23.         }
  24.     }
  25. }
  26.  
  27. var ids = new Array('errorname', 'erroremail', 'errorphone', 'erroraddress');
  28. var isValid = new Array();
  29.  
  30. for (var i=0; i<ids.length; i++)
  31. {
  32.     isValid[ids[i]] = false;
  33. }
  34.  
  35.  
  36. function validate(value,id)
  37. {
  38.     srv="process.php?"+value
  39.     request.open('GET',srv)
  40.     request.onreadystatechange=        function()
  41.                                     {
  42.                                         if(request.readyState==4 && request.status==200)
  43.                                         {
  44.                                             resp = request.responseText;
  45.                                             if (resp == '<font color=blue>OK!</font>')
  46.                                             {    
  47.                                                 isValid[id] = true;
  48.                                                 document.getElementById(id).innerHTML=request.responseText;
  49.                                             }
  50.                                             else
  51.                                             {
  52.                                                 isValid[id] = false;
  53.                                                 document.getElementById(id).innerHTML=request.responseText;                                                                                                
  54.                                             }
  55.  
  56.                                         }
  57.                                     }
  58.     request.send(null)
  59. }
  60.  
  61. function validateAll(value,id) 
  62. {
  63.     for (var i=0; i<ids.length; i++)
  64.     if (isValid[ids[i]]==false) 
  65.     {
  66.         //add any error message here
  67.         alert("Damn!");
  68.         return false;
  69.     }
  70.     srv="process.php?"+value
  71.     request.open('GET',srv)
  72.     request.onreadystatechange=        function()
  73.                                     {
  74.                                         document.getElementById(id).innerHTML=request.responseText;
  75.                                     }
  76.     request.send(null)
  77. }
  78.  
main.html
[html]
<script language="javascript" src="validate.js"></script>
<table width="500">
<tr>
<td>Username:</td>
<td><input type="text" name="username" autocomplete="off" onchange="validate('name='+escape(this.value),'err orname')" /></td>
</tr>
<tr><td colspan="2"><div id="errorname"></div></td></tr>

<tr>
<td>Email:</td>
<td><input type="text" name="email" autocomplete="off" onchange="validate('email='+escape(this.value),'er roremail')" /></td>
</tr>
<tr><td colspan="2"><div id="erroremail"></div></td></tr>

<tr>
<td>Phone:</td>
<td><input type="text" name="phone" autocomplete="off" onchange="validate('phone='+escape(this.value),'er rorphone')" /></td>
</tr>
<tr><td colspan="2"><div id="errorphone"></div></td></tr>

<tr>
<td>Address:</td>
<td><input type="text" name="address" autocomplete="off" onchange="validate('address='+escape(this.value),' erroraddress')" /></td>
</tr>
<tr><td colspan="2"><div id="erroraddress"></div></td></tr>

<tr>
<td>&nbsp;</td>
<td><input type="submit" name="submit" onclick="validateAll('submit=ok','errorsubmit')" value="Submit" /></td>
</tr>
<tr><td colspan="2"><div id="errorsubmit"></div></td></tr>
</table>
</body>
</html>
[/html]

process.php
[php]
<?php
include('db.php');

function valid_name($str)
{
return ( ! preg_match("/^([-a-z0-9])+$/i", $str)) ? FALSE : TRUE;
}

function valid_phone($str)
{
return ( ! preg_match("/^([0-9])+$/i", $str)) ? FALSE : TRUE;
}

function valid_email($str)
{
return ( ! preg_match("/^([a-z0-9\+_\-]+)(\.[a-z0-9\+_\-]+)*@([a-z0-9\-]+\.)+[a-z]{2,6}$/ix", $str)) ? FALSE : TRUE;
}

if($_GET['name'])
{
$name=$_GET['name'];
$q1=mysql_query("SELECT username FROM users WHERE username = '$name'") or die(mysql_error());

if(valid_name($name)==FALSE) die('<font color=red>Invalid username</font>');

if($name==''|| strlen($name)<3) die('<font color=red>Username must be at least 3 characters</font>');

if(mysql_num_rows($q1)!=0) die ('<font color=red>Name is in use');

else
{
echo '<font color=blue>OK!</font>';
}
}

if($_GET['email'])
{
$email=$_GET['email'];

if(($email=='')||(valid_email($email)==FALSE)) die("<font color=red>Invalid Email Address!</font>");

else
{
echo '<font color=blue>OK!</font>';
}
}

if($_GET['phone'])
{
$phone=$_GET['phone'];

if(($phone=='')|| (valid_phone($phone)==FALSE)) die("<font color=red>Invalid phone number!</font>");

else
{
echo '<font color=blue>OK!</font>';
}
}

if($_GET['address'])
{
$address=$_GET['address'];

if($address=='') die("<font color=red>Address has not been filled in!</font>");

else
{
echo '<font color=blue>OK!</font>';
}
}

if($_GET['submit'])
{
echo '<font color=blue>Ok, you are done!</font>';
}

?>
[/php]

I think my code is much simpler than those samples found on the Internet though I don't know what limit mine may have. anyone can help me to debug?

ah, and can you help me to replace the boring "OK" with an image signing that you satisfy something. this sign should be placed on the right of the text field while the error message is still where it used to be.

once again, thanks alot :)
Apr 10 '08 #5
acoder
16,027 Expert Mod 8TB
I think my code is much simpler than those samples found on the Internet though I don't know what limit mine may have. anyone can help me to debug?
I haven't tested your code, but I would say that you should use encodeURIComponent() instead of escape().

ah, and can you help me to replace the boring "OK" with an image signing that you satisfy something. this sign should be placed on the right of the text field while the error message is still where it used to be.
Just use an img tag.
Apr 11 '08 #6

Sign in to post your reply or Sign up for a free account.

Similar topics

31
by: Tony | last post by:
I just noticed that prototype.js is one of the files in the Ajax.NET distribution - I'm pretty concerned about this. Does anyone know if this is the same "prototype.js" that is not well-liked...
1
by: AECL_DEV | last post by:
Hello Everyone, Ive seen alot of people saying that the best way to AJAX Validate a form is through the submit button, because validation should be synchronous. Im wondering, is there any good...
5
by: Martin | last post by:
Hello NG, I've been doing some AJAX for a few weeks now. The basics worked fine so far, but now I've got the following problem which I can't solve: With AJAX you typically update/replace only...
1
by: John Chan | last post by:
Hi, Im doing a maintenance application in ajax and coldfusion at work on IE6 exclusively. I have a save button on each form and i have to do various validations server side and on client side...
5
by: lucyh3h | last post by:
Hi, I am trying to use XMLHttpRequest to do server side validation. I have several fields on a form and a submit button. The submit button has an event assocated with it when clicked. The...
7
ak1dnar
by: ak1dnar | last post by:
Hi, I got this scripts from this URL There is Error when i submit the form. Line: 54 Error: 'document.getElementbyID(....)' is null or not an object What is this error. Complete Files
3
rizwan6feb
by: rizwan6feb | last post by:
Hi experts! Recently i was working on "Form Validation Using Ajax". My form validation was creating problem, when a user changes focus too quickly. I had a post related to this, but was unable to...
1
by: Mark B | last post by:
This is my first try at using AJAX. I want the calendars to be enabled if the user checks CheckBox1. It works OK for a normal all page refresh but once I introduced the AJAX code it stopped...
3
pradeepjain
by: pradeepjain | last post by:
hii guys , I wanna share a very gud ajax validation script with php... Ajax Form Validation - sForm | chains.ch weblog I am very new to ajax .So i wanna small help....i want to...
0
by: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
0
by: ryjfgjl | last post by:
If we have dozens or hundreds of excel to import into the database, if we use the excel import function provided by database editors such as navicat, it will be extremely tedious and time-consuming...
0
by: ryjfgjl | last post by:
In our work, we often receive Excel tables with data in the same format. If we want to analyze these data, it can be difficult to analyze them because the data is spread across multiple Excel files...
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
0
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However,...
0
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can...
0
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers,...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.