简体   繁体   中英

ajax form validation with php and javascript

I'm working on a simple form and validating it through javascript php and AJAX.

Here is the html form snippet just for the password:

Password:
<input type="password" name="password" id="password"
            onblur="checkUserInputs('password')"
        <span id="password-warning"></span>
<input type="button" name="signup" id="signup" 
            value ="Sign Up" class="button signup-button" 
                    onclick="signUp()">
            <span id="status-field"></span>

Here is the checkUserInput() snippet that fires up on onblur event:

     function checkUserInputs(inputId){
        var inputField = document.getElementById("password");
        var varName = "checkPassword"; /variable name to send to php
        var functionToCall = "check_password";//php calls corresponding function based on this string value       
    if(inputField.value != ""){
        //creates ajax object
        var ajax = createAjax("POST", "core/proccess_signup.php");
        ajax.setRequestHeader("Content-type","application/x-www-form-urlencoded"); 
        ajax.onreadystatechange = function(){
            if(ajaxReady(ajax)){
               //display error massage
                warningDiv.innerHTML = ajax.responseText;    
            }
        }
        //now data to php scripts for validation           ajax.send(varName+"="+inputField.value+"&functionToCall="+functionToCall);
    }   
}

SignUp() fires up when clicking signup button:

function signUp(){
    var password = document.getElementById("password").value;
    //rest of the code to get other inputs values...
    //status div to display errors
    var statusDiv = document.getElementById("status-field");    
    if(password !="")//I have other checks too, just shortened the code here {
        //setup ajax
        var ajax = createAjax("POST", "core/proccess_signup.php");
        ajax.setRequestHeader("Content-type","application/x-www-form-urlencoded"); 
        ajax.onreadystatechange = function(){
            if(ajaxReady(ajax)){

                if(ajax.responseText == "success"){ //registartion was successful
                    document.getElementById("signup-form").innerHTML = 
                      "Registration was successful";
                }else{
                    statusDiv.innerHTML = "Please check the error massages";
                }       
            }
        }
        //send all of the data to php scripts for validation            ajax.send("functionToCall=signup&username="+username+"&password="+password);
    }else{
        statusDiv.innerHTML = "Please fill out all of the form data";
        return;
    }    
}

Validate the data in php:

$functionToCall = $_REQUEST['functionToCall'];
if($functionToCall == "check_password"){
    check_password();
}else if($functionToCall == "signup"){
   check_password();    
   signup();
}
function check_password(){
    if(isset($_POST['checkPassword'])) {
        $pass = $_POST['checkPassword'];
        if(strlen($pass)< 6 || strlen($pass) > 20){
            echo 'password must be min 6 and max 20 characters';
            exit();
        } 
        if(preg_match("/\s/", $pass)) {
            echo 'Password can not be empty or contain spaces';
            exit();
        }
        echo '';
        return true; //if all is good return true so i can check if password validation passed successfully
    }
}

Here is the signup function

  function signup(){
        if(isset($_POST['username'])) {
            //here I check just the password    
            if(check_password()){
                echo 'success';
                exit(); 
            }
        }

well if password entered correctly with no white spaces and length between 6-20, check_password() should be set to true and echo 'success' should be executed, but it DOESN'T. this drives me nuts.

Why echo 'success' never gets executed? Take a look at the code and tell me what I'm doing wrong.

The main problem that I can see is that the check_password function looks for isset($_POST['checkPassword']).

That function is called again by the second ajax request, which doesn't post that value. It posts password.

I would strongly recommend using xdebug if you aren't already. It really helps when stepping through this kind of thing. xdebug

Here's a quick fix to pop in check_password function.

    if(isset($_POST['checkPassword']) || isset($_POST['password']) ) {
    $pass = (isset($_POST['checkPassword']) ) ? $_POST['checkPassword'] : $_POST['password'];

Also you call the check_password function twice. It might be better to store the return value of that as a variable then pass as a parameter.

First call

if($functionToCall == "signup"){
check_password();    
signup();

Second Call (in signup function)

        if(check_password()){
        echo 'success';
        exit();
    }

I had to mess with the js a little to make that work , but I'm guessing that was just some mishaps in abbreviating the code for simplicity. Changes:

  1. Ajax request wasn't working, so edited.

  2. username var wasn't set, so hardcoded to foobar.

Here is the full html page

        <!DOCTYPE html>
        <html>
        <head>
        <meta charset="ISO-8859-1">
        <title>TEST</title>

        <script>

        function checkUserInputs(inputId){


            var inputField = document.getElementById("password").value;
            var varName = "checkPassword"; 
            var functionToCall = "check_password";
            var warningDiv = document.getElementById("password-warning");

        if( inputField != ""){

                var params = varName + "=" + inputField + "&functionToCall=" + functionToCall;
                var xmlhttp=new XMLHttpRequest();
                xmlhttp.onreadystatechange=function()
                  {
                  if (xmlhttp.readyState==4 && xmlhttp.status==200)
                    {
                        warningDiv.innerHTML = xmlhttp.responseText; 
                    }
                  }

                xmlhttp.open("POST","core/proccess_signup.php",true);
                xmlhttp.setRequestHeader("Content-type","application/x-www-form-urlencoded");
                xmlhttp.send( params );
            }   
        }

        function signUp(){


            var password = document.getElementById("password").value;
            //rest of the code to get other inputs values...
            //status div to display errors
            var statusDiv = document.getElementById("status-field");    
            if(password !=""){ //I have other checks too, just shortened the code here 

                var xmlhttp=new XMLHttpRequest();
                xmlhttp.onreadystatechange=function()
                  {
                  if (xmlhttp.readyState==4 && xmlhttp.status==200)
                    {
                        if( xmlhttp.responseText == "success"){ // registration was successful
                            statusDiv.innerHTML = "Registration was successful";
                        }
                        else{
                            statusDiv.innerHTML = "Please check the error messages";
                        }
                    }
                  }

                xmlhttp.open("POST","core/proccess_signup.php",true);
                xmlhttp.setRequestHeader("Content-type","application/x-www-form-urlencoded");
                xmlhttp.send("functionToCall=signup&username=foobar&password="+password);
            }
            else
            {
                statusDiv.innerHTML = "Please fill out all of the form data";
                return;
            }    
        }


        </script>

        </head>
        <body>


        <input type="password" name="password" id="password" onblur="checkUserInputs('password')" />
                <span id="password-warning"></span>
        <input type="button" name="signup" id="signup" value ="Sign Up" class="button signup-button" onclick="signUp()" />
                    <span id="status-field"></span>
        </body>
        </html>

Here is the php (I haven't taken out the duplicate function call)

            <?php
        $functionToCall = $_REQUEST['functionToCall'];
        if($functionToCall == "check_password"){
            check_password();
        }else if($functionToCall == "signup"){
            check_password();
            signup();
        }

        function check_password(){

            if(isset($_POST['checkPassword']) || isset($_POST['password']) ) {
                $pass = (isset($_POST['checkPassword']) ) ? $_POST['checkPassword'] : $_POST['password'];

                if(strlen($pass)< 6 || strlen($pass) > 20){
                    echo 'password must be min 6 and max 20 characters';
                    exit();
                }
                if(preg_match("/\s/", $pass)) {
                    echo 'Password can not be empty or contain spaces';
                    exit();
                }
                echo '';
                return true; //if all is good return true so i can check if password validation passed successfully
            }
        }

        function signup(){


            if(isset($_POST['username'])) {
                //here I check just the password
                if(check_password()){
                    echo 'success';
                    exit();
                }
            }
        }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM