473,729 Members | 2,405 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Error in Form Validation PHP/AJAX

ak1dnar
1,584 Recognized Expert Top Contributor
Hi, I got this scripts from this URL

There is Error when i submit the form.

Line: 54
Error: 'document.getEl ementbyID(....) ' is null or not an object
What is this error.

Complete Files

index.php

[PHP]<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dt d">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">

<head>
<title>Ajax Form</title>

<script type="text/javascript" src="validate.j s"></script>

</head>

<body>
<fieldset>
<legend>Ajax Form</legend>


<form name="form1" id="form1" method="post" action="formval idation.php?val idationtype=php " onSubmit="retur n validate();">
<table width="500">
<tr>
<td width="130">Use rname </td>
<td width="170"><in put type="text" name="user" tabindex="1" id="user" class="validate required none usermsg"/></td>
<td id ="usermsg" class="rules">R equired</td>
</tr>

<tr>
<td>Email </td>
<td><input type="text" name="email" tabindex="2" id="email" class="validate required email emailmsg" /></td>
<td id="emailmsg" class="rules">R equired</td>
</tr>

<tr>
<td><input type="submit" name="Submit" value="Submit" tabindex="5" /></td>
</tr>

</table>

</form>
</fieldset>
</body>


</html>
[/PHP]

formvalidation. php
[PHP]<?php
//After the form is submitted or onblur, request the validation type
$validationtype = $_GET["validationtype "]; //validationtype is ajax or php
$continueSubmit = true ; //global var if the form is valid. used only for php validationtype.

switch ($validationtyp e)
{
case 'ajax':
ProcessAjax(); //if validationtype is ajax go to processajax function
break;
case 'php':
processPHP();//if it is php call processphp runction
break;
}

function ProcessAjax()
{
$required = $_GET["sRequired"];//$required holds if the field is required. will be "required" or "notrequire d"
$typecheck = $_GET["sTypeCheck "];//$typecheck holds additional requirements like email or phone
$val = $_GET["val"];

//validateRequire d checks if it is required and then sends back feedback
validateRequire d($required,$va l,$typecheck);

/*check to see which typecheck (eg. email, date, etc.) was entered as the second variable in the validateMe() function
check the different cases passed in from the validateMe function. Send back the appropriate information*/
switch ($typecheck)
{
case 'date':
validateDate($v al);
break;
case 'email':
validateEmail($ val);
break;
}
}

//If the url string value for validationtype was PHP, you will be validating through this server side function
function processPHP()
{
//request the forms variables
$user = $_POST["user"];
$email= $_POST["email"];
global $continueSubmit ;

//check to see if the different form fields are valid
echo "Username: ";
validateRequire d("required", $user, "none");//validate user
echo "<br />";

echo "Email: ";
validateEmail($ email) ;//validate email

//if continue is not 0 then continue with the form submission
if ($continueSubmi t)
{
//submit your form
}

}

//--------------------------VALIDATION FUNCTIONS -----------------

//Function to validate if the field is required. It just checks to see if the field is empty.
function validateRequire d($required,$va l,$typecheck)
{

// if it is required check to see if it validates
if ($required == "required")
{
if ($val == "")
{
// if val is blank then then the field is invalid
echo "Required";
exit(); //we do not need to check for anything else so exit the validation
}

if ($val !== "" && $typecheck == "none")
{
// if val is not blank and there are no further validation checks ("none") respond with a thank you for feedback
echo "Thank You";
}
}
// if it is not required or typecheck is not none, the script will continue to validate
}


function validateEmail($ val)
{
global $continueSubmit ;
// check the email address with a regex function
//regular expression is from http://regexlib.com/.
//To learn more about them, http://www.silverstone s.com/thebat/Regex.html#intr o has a pretty good tutorial
if (ereg ("^([0-9a-zA-Z]+[-._+&])*[0-9a-zA-Z]+@([-0-9a-zA-Z]+[.])+[a-zA-Z]{2,6}$", $val, $regs))
{
echo "Thank You";
}
else
{
$continueSubmit = false;
echo "Invalid Email Address";
}
}
[/PHP]

validate.js

Expand|Select|Wrap|Line Numbers
  1. window.onload = attachFormHandlers;
  2.  
  3. var gShow; //variable holding the id where feedback will be sent to.
  4. var sUrl = "formvalidation.php?validationtype=ajax&val=";//url is the page which will be processing all of the information.  it is important to make sure validationtype is ajax
  5. var gErrors = 0; //number of errors is set to none to begin with
  6. var http = getHTTPObject();//don't worry about this
  7.  
  8.  
  9.  
  10. function attachFormHandlers()
  11. {
  12.     var form = document.getElementById('form1') 
  13.  
  14.     if (document.getElementsByTagName)//make sure were on a newer browser
  15.     {
  16.         var objInput = document.getElementsByTagName('input');
  17.         for (var iCounter=0; iCounter<objInput.length; iCounter++)
  18.         objInput[iCounter].onblur = function(){return validateMe(this);} //attach the onchange to each input field
  19.     }
  20.     form.onsubmit = function(){return validate();} //attach validate() to the form
  21. }
  22.  
  23.  
  24.  
  25.  
  26. /*validateMe is the function called with onblur each time the user leaves the input box
  27. passed into it is the value entered, the rules (which you could create your own), and the id of the area the results will show in*/
  28. function validateMe(objInput) {
  29.  
  30.     sVal = objInput.value; //get value inside of input field
  31.  
  32.     sRules = objInput.className.split(' '); // get all the rules from the input box classname
  33.     sRequired = sRules[1]; // determines if field is required or not
  34.     sTypeCheck = sRules[2]; //typecheck are additional validation rules (ie. email, phone, date)
  35.     gShow = sRules[3]; //gShow is the td id where feedback is sent to.
  36.  
  37.     //sends the rules and value to the asp page to be validated
  38.     http.open("GET", sUrl + (sVal) + "&sRequired=" + (sRequired) + "&sTypeCheck=" + sTypeCheck, true);
  39.  
  40.     http.onreadystatechange = handleHttpResponse;     // handle what to do with the feedback 
  41.     http.send(null);  
  42. }
  43.  
  44.  
  45. function handleHttpResponse() {
  46.     //if the process is completed, decide to do with the returned data
  47.     if (http.readyState == 4) 
  48.       {
  49.  
  50.           sResults = http.responseText.split(","); //results is now whatever the feedback from the asp page was
  51.         //whatever the variable glo_show's (usermsg for example) innerHTML holds, is now whatever  was returned by the asp page. 
  52.         document.getElementById(gShow).innerHTML = "";
  53.         document.getElementById(gShow).appendChild(document.createTextNode(sResults[0]));
  54.       }
  55. }
  56.  
  57.  
  58. function validate()
  59. {
  60. var tables; 
  61.  
  62. tables = document.getElementsByTagName('td')
  63.  
  64.     for (i=0; i<tables.length; i++)//loop through all the <td> elements 
  65.     {
  66.         // if the class name of that td element is rules check to see if there are error warnings
  67.         if (tables[i].className == "rules")
  68.         {
  69.             //if there is a thank you or its blank then it passes
  70.             if (tables[i].innerHTML == 'Thank You' || tables[i].innerHTML == '' )
  71.             {
  72.                 tables[i].style.color = '#000000';//the color is changed to black or stays black
  73.             }
  74.             else
  75.             {
  76.                 gErrors = gErrors + 1; //the error count increases by 1
  77.                 tables[i].style.color = '#ff0000';//error messages are changed to red
  78.             }
  79.         }
  80.     }
  81.  
  82.     if (gErrors > 0)
  83.     {
  84.         //if there are any errors give a message
  85.         alert ("Please make sure all fields are properly completed.  Errors are marked in red!");
  86.         gErrors = 0;// reset errors to 0
  87.         return false;
  88.     }
  89.     else return true;
  90.  
  91. }
  92.  
  93.  
  94. function getHTTPObject() {
  95.     var xmlhttp;
  96.     /*@cc_on
  97.     @if (@_jscript_version >= 5)
  98.     try {
  99.         xmlhttp = new ActiveXObject("Msxml2.XMLHTTP");
  100.     } catch (e) {
  101.       try {
  102.         xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
  103.       } catch (E) {
  104.         xmlhttp = false;
  105.       }
  106.     }
  107.   @else
  108.   xmlhttp = false;
  109.   @end @*/
  110.     if (!xmlhttp && typeof XMLHttpRequest != 'undefined') {
  111.         try 
  112.         {
  113.             xmlhttp = new XMLHttpRequest();
  114.         } catch (e) {
  115.         xmlhttp = false;
  116.         }
  117.     }
  118.     return xmlhttp;
  119. }
Mar 22 '07 #1
7 3617
acoder
16,027 Recognized Expert Moderator MVP
document.getEle mentById perhaps? (unless it was a typo here).
Mar 22 '07 #2
ak1dnar
1,584 Recognized Expert Top Contributor
document.getEle mentById perhaps? (unless it was a typo here).
Sorry Acoder I didn't get you.
Mar 22 '07 #3
acoder
16,027 Recognized Expert Moderator MVP
Sorry Acoder I didn't get you.
Your error is:
Line: 54
Error: 'document.getEl ementbyID(....) ' is null or not an object
The 'b' should be a capital 'B', but I wasn't sure if you'd typed it out here incorrectly or whether it really was that mistake.
Mar 22 '07 #4
ak1dnar
1,584 Recognized Expert Top Contributor
Sorry Its my mistake. these scripts are working but once i submit the page with out values this error will come.

Line: 59
Char: 6
Error: 'document.getEl ementById(...)' is null or not an object.
Code:0

Again there is another bug, once i submit the page with correct values second page will appear. but when i press the back button and go back to the page same values are there but when i submit Validation errors will generate.
Mar 22 '07 #5
boffa
3 New Member
Hi There

Itīs a bit late comming in to this question now but still I have the same problem and maybe have som extra information.

The error Error: 'document.getEl ementById(...)' is null or not an object
only happend when you are not entering any information into a field that is NOT reqiured to be filled in and thereby not validated.

Sounds strange to me, but that is how it works out for me. Still the error is there but itīs less of an problem now. I know, it didnīt cure the problem but it made it easier to live with.

If someone has the real cure to this problem I would be greatful because I just simply cant figure it out.
Aug 18 '07 #6
jx2
228 New Member
line 53 in *.js file there is unnecesary space

document.getEle mentById(gShow) .appendChild(do cumen t.createTextNod e(sResults[0]));

documen t.createT...

?
Aug 18 '07 #7
boffa
3 New Member
Nop, thatīs not it since I allready fixed that in my .js file. But thanks for your reply.
Aug 20 '07 #8

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

Similar topics

4
11880
by: josh.dutcher | last post by:
I'm trying to set up a simple "change your password" form. I've got an AJAX process that is checking the new password the user enters against their current password to make sure they're changing it. This function is firing via the password field's onBlur event handler. I want to do some other form validation using the form's onSubmit handler (onSubmit="return validateForm();", and if all those conditions are met, the form submits. ...
1
1871
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 way to validate a form field by field like AJAX would do, but to keep it synchronous? i.e. one action, one validation. Thanks,
5
1937
by: Advo | last post by:
Basically, im redesigning a form page on our website. Currently the user submits the form, it does a few javascript checks and either submits to the "processstuff.php" page, or gives the user a JS error message.. where they have to go back and fill the details in. Im trying to optimise and make this form/page as best as it can be. Do you think it would be a better idea to continue using JS or use JS then submit to the php page(where...
0
1456
by: john_c | last post by:
Sometimes I get this error in an aspx page: Invalid postback or callback argument. Event validation is enabled using <pages enableEventValidation="true"/in configuration or <%@ Page EnableEventValidation="true" %in a page. For security purposes, this feature verifies that arguments to postback or callback events originate from the server control that originally rendered them. If the data is valid and expected, use the...
1
2112
by: nRk | last post by:
Hi, I am working on asp.net 2.0 with Visual Studio 2005. My asp.net project contains one Masterpage. I exposed my asp.net project in my machine (Windows XP with IIS 5.1) and access using "http://localhost/..." In user registration form I included validation controls (Required, comparer, ..) in my machine validation controls showing error messages
2
19483
hyperpau
by: hyperpau | last post by:
Before anything else, I am not a very technical expert when it comes to VBA coding. I learned most of what I know by the excellent Access/VBA forum from bytes.com (formerly thescripts.com). Ergo, I will be writing this article intended for those who are in the same level, or maybe lower, of my technical knowledge. I would be using layman's words, or maybe, my own words as how I understand them, hoping, you will understand it the same way that...
3
2112
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 improve that script with adding checkbox,radiobutton validation and dropdown list validation . but i am not able to do it.....any one can add his/her code into that ajax script..tht i can have a look at it.. And i have found a small bug in tht script...
2
4906
scubak1w1
by: scubak1w1 | last post by:
Hello, I am building a form that collects some data about a file and throws it into a PosgreSQL database and also allows the user to upload and process the file using PHP's $_FILES... i.e., <input type="file" name="file" id="file" size="50"/> Action is a PHP_SELF, method is POST, check with array_key_exists, etc... anyway..... :-) The form works just fine if all of the data is entered correctly...
0
2897
hyperpau
by: hyperpau | last post by:
Before anything else, I am not a very technical expert when it comes to VBA coding. I learned most of what I know by the excellent Access/VBA forum from bytes.com (formerly thescripts.com). Ergo, I will be writing this article intended for those who are in the same level, or maybe lower, of my technical knowledge. I would be using layman's words, or maybe, my own words as how I understand them, hoping, you will understand it the same way that...
0
8763
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 effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
9284
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
9202
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
1
6722
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
6022
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
4528
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
0
4796
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
3238
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
2
2683
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.

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.