使用php和javascript进行ajax表单验证

时间:2015-08-28 21:18:35

标签: javascript php ajax

我正在处理一个简单的表单并通过javascript php和AJAX进行验证。

以下是仅用于密码的html表单摘要:

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>

以下是触发onb​​lur事件的checkUserInput()代码段:

     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()会激活:

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;
    }    
}

验证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
    }
}

这是注册功能

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

如果密码正确输入且没有空格且长度在6-20之间,check_password()应该设置为true并且应该执行echo'success',但它不会。这让我疯了。

为什么echo'成功'永远不会被执行?看看代码并告诉我我做错了什么。

1 个答案:

答案 0 :(得分:1)

我可以看到的主要问题是check_password函数查找isset($ _ POST ['checkPassword'])。

第二个ajax请求再次调用该函数,该请求不会发布该值。它发布了密码。

如果你还没有,我强烈推荐使用xdebug。踩过这种东西真的很有帮助。 xdebug

这是一个快速解决方法,可以在check_password函数中弹出。

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

您也可以两次调用check_password函数。最好将其返回值存储为变量,然后作为参数传递。

先致电

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

第二次通话(在注册功能中)

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

我不得不将js弄得一点点才能完成这项工作,但我猜这只是为了简化而缩写代码的一些不幸。 变化:

  1. Ajax请求无效,因此已编辑。

  2. 用户名var未设置,因此硬编码为foobar。

  3. 这是完整的html页面

            <!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>
    

    这是php(我没有取出重复的函数调用)

                <?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();
                    }
                }
            }