【问题标题】:ajax form validation with php and javascript使用 php 和 javascript 进行 ajax 表单验证
【发布时间】:2015-11-23 15:19:04
【问题描述】:

我正在制作一个简单的表单并通过 javascript php 和 AJAX 对其进行验证。

这里是 html 表单 sn-p 仅用于密码:

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>

这是在 onblur 事件中触发的checkUserInput() sn-p:

     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 'success' 永远不会被执行?看看代码,告诉我我做错了什么。

【问题讨论】:

  • 你确定它不应该是if(preg_match('/\s/', $pass))吗?此外,此正则表达式不检查字符串是否为空。为此,您可以尝试使用if(preg_match('/\s|^$/', $pass))
  • 谢谢,我已经修好了

标签: javascript php ajax


【解决方案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。

这是完整的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();
                }
            }
        }

【讨论】:

  • 谢谢!我会根据您的评论仔细检查并修复我的代码
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-05-17
  • 1970-01-01
相关资源
最近更新 更多