Error in Form Validation PHP/AJAX

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • ak1dnar
    Recognized Expert Top Contributor
    • Jan 2007
    • 1584

    Error in Form Validation PHP/AJAX

    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

    Code:
    window.onload = attachFormHandlers;
    
    var gShow; //variable holding the id where feedback will be sent to.
    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
    var gErrors = 0; //number of errors is set to none to begin with
    var http = getHTTPObject();//don't worry about this
    
    
    
    function attachFormHandlers()
    {
    	var form = document.getElementById('form1') 
    
    	if (document.getElementsByTagName)//make sure were on a newer browser
    	{
    		var objInput = document.getElementsByTagName('input');
    		for (var iCounter=0; iCounter<objInput.length; iCounter++)
    		objInput[iCounter].onblur = function(){return validateMe(this);} //attach the onchange to each input field
    	}
    	form.onsubmit = function(){return validate();} //attach validate() to the form
    }
    
    
    
    
    /*validateMe is the function called with onblur each time the user leaves the input box
    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*/
    function validateMe(objInput) {
    
    	sVal = objInput.value; //get value inside of input field
    	
    	sRules = objInput.className.split(' '); // get all the rules from the input box classname
    	sRequired = sRules[1]; // determines if field is required or not
    	sTypeCheck = sRules[2]; //typecheck are additional validation rules (ie. email, phone, date)
        gShow = sRules[3]; //gShow is the td id where feedback is sent to.
      
    	//sends the rules and value to the asp page to be validated
    	http.open("GET", sUrl + (sVal) + "&sRequired=" + (sRequired) + "&sTypeCheck=" + sTypeCheck, true);
      
    	http.onreadystatechange = handleHttpResponse; 	// handle what to do with the feedback 
    	http.send(null);  
    }
    
    
    function handleHttpResponse() {
    	//if the process is completed, decide to do with the returned data
    	if (http.readyState == 4) 
      	{
    		
      		sResults = http.responseText.split(","); //results is now whatever the feedback from the asp page was
    		//whatever the variable glo_show's (usermsg for example) innerHTML holds, is now whatever  was returned by the asp page. 
        	document.getElementById(gShow).innerHTML = "";
    		document.getElementById(gShow).appendChild(document.createTextNode(sResults[0]));
      	}
    }
    
    
    function validate()
    {
    var tables; 
    
    tables = document.getElementsByTagName('td')
    
    	for (i=0; i<tables.length; i++)//loop through all the <td> elements 
    	{
    		// if the class name of that td element is rules check to see if there are error warnings
    		if (tables[i].className == "rules")
    		{
    			//if there is a thank you or its blank then it passes
    			if (tables[i].innerHTML == 'Thank You' || tables[i].innerHTML == '' )
    			{
    				tables[i].style.color = '#000000';//the color is changed to black or stays black
    			}
    			else
    			{
    				gErrors = gErrors + 1; //the error count increases by 1
    				tables[i].style.color = '#ff0000';//error messages are changed to red
    			}
    		}
    	}
    		
    	if (gErrors > 0)
    	{
    		//if there are any errors give a message
    		alert ("Please make sure all fields are properly completed.  Errors are marked in red!");
    		gErrors = 0;// reset errors to 0
    		return false;
    	}
    	else return true;
    
    }
    
    
    function getHTTPObject() {
    	var xmlhttp;
    	/*@cc_on
    	@if (@_jscript_version >= 5)
    	try {
    		xmlhttp = new ActiveXObject("Msxml2.XMLHTTP");
    	} catch (e) {
          try {
            xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
          } catch (E) {
            xmlhttp = false;
          }
        }
      @else
      xmlhttp = false;
      @end @*/
    	if (!xmlhttp && typeof XMLHttpRequest != 'undefined') {
    		try 
    		{
    			xmlhttp = new XMLHttpRequest();
    		} catch (e) {
    		xmlhttp = false;
    		}
    	}
    	return xmlhttp;
    }
  • acoder
    Recognized Expert MVP
    • Nov 2006
    • 16032

    #2
    document.getEle mentById perhaps? (unless it was a typo here).

    Comment

    • ak1dnar
      Recognized Expert Top Contributor
      • Jan 2007
      • 1584

      #3
      Originally posted by acoder
      document.getEle mentById perhaps? (unless it was a typo here).
      Sorry Acoder I didn't get you.

      Comment

      • acoder
        Recognized Expert MVP
        • Nov 2006
        • 16032

        #4
        Originally posted by ajaxrand
        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.

        Comment

        • ak1dnar
          Recognized Expert Top Contributor
          • Jan 2007
          • 1584

          #5
          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.

          Comment

          • boffa
            New Member
            • Aug 2007
            • 3

            #6
            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.

            Comment

            • jx2
              New Member
              • Feb 2007
              • 228

              #7
              line 53 in *.js file there is unnecesary space

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

              documen t.createT...

              ?

              Comment

              • boffa
                New Member
                • Aug 2007
                • 3

                #8
                Nop, that´s not it since I allready fixed that in my .js file. But thanks for your reply.

                Comment

                Working...