jquery - 表单 ajax 数据库检查唯一值

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/17359277/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 18:53:36  来源:igfitidea点击:

jquery - form ajax database check for unique value

jqueryvalidationpdo

提问by Lacer

using

使用

  • jquery validator plugin
  • jquery
  • jquery 验证器插件
  • 查询

try to:

尝试:

  • make sure a username doesn't exist in the database
    • have a form + a field + remote check
    • i want to let jquery check using ajax if it exists.
  • 确保数据库中不存在用户名
    • 有一个表单+一个字段+远程检查
    • 我想让 jquery 使用 ajax 检查它是否存在。

what works:

什么有效:

  • check-username.php does work by itself
  • check-username.php 确实可以自己工作

what doesn't

什么没有

  • form doesn't seem to be able to pass return boolean value to validate the remote jquery validation
  • how do I get it to pass the value so that the field can be validated?
  • 表单似乎无法通过返回布尔值来验证远程 jquery 验证
  • 我如何让它传递值以便可以验证该字段?

HTML

HTML

    <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.1/jquery.min.js" type="text/javascript"></script>
    <script src="http://ajax.aspnetcdn.com/ajax/jquery.validate/1.11.1/jquery.validate.min.js" type="text/javascript"></script> 
    <script language="javascript" src="validate.js"></script>

    <meta name="generator" content="" />
    <style type="text/css"></style>
  </head>
<body>

<form action="/" method="post" id="register-form">
    <div>
        <label for="username">Username<font color="red">*</font>:</label> 
        <input type="text" name="username" size="20" id="username" />
    </div>
    <div>
        <input type="submit" name="submit" value="submit" />
    </div>
</form>
</body>
</html>

JQUERY Validate

JQUERY 验证

$().ready(function() {
    // validate signup form on keyup and submit
    $("#register-form").validate({
        rules: {
            username: {
                required: true,
                remote: "check-username.php"
                },
        },
        messages: {
            username:{
                remote: "This username is already taken! Try another."
            },
        },
    });
});

Check-USERNAME.php

检查-USERNAME.php

<?php

$searchVal = $_POST['username'];

try {
    $dbh = new PDO("mysql:host=$hostname;dbname=$data", $username, $password);

    $sql = "SELECT * FROM users WHERE USERNAME = " . "'" . $searchVal .  "'";
    $stmt = $dbh->query($sql);
    $result = $stmt->fetch(PDO::FETCH_ASSOC);

   if($result>0){
     return true;
   }else {
     return false;
   }

    $dbh = null;
    }
        catch(PDOException $e)
    {
        echo $e->getMessage();
    }       
?>

回答by Erdo Dirgagautama

In order to validate value to server side, you should add new Validation Method.

为了验证服务器端的值,您应该添加新的验证方法。

$().ready(function() {

    $.validator.addMethod("checkUserName", 
        function(value, element) {
            var result = false;
            $.ajax({
                type:"POST",
                async: false,
                url: "check-username.php", // script to validate in server side
                data: {username: value},
                success: function(data) {
                    result = (data == true) ? true : false;
                }
            });
            // return true if username is exist in database
            return result; 
        }, 
        "This username is already taken! Try another."
    );

    // validate signup form on keyup and submit
    $("#register-form").validate({
        rules: {
            "username": {
                required: true,
                checkUserName: true
            }
        }
    });
});        

As stated above, method checkUserName will verify to server side and give error message "This username is already taken! Try another." if username is not exist.

如上所述,方法 checkUserName 将验证到服务器端并给出错误消息“此用户名已被占用!尝试另一个。”如果用户名不存在。

For more info and examples about jQuery Validation and its method : click here.

有关 jQuery 验证及其方法的更多信息和示例:单击此处

Hopefully this help.

希望这有帮助。

回答by Amani

Didn't check the rest of your code, but try this:

没有检查你的其余代码,但试试这个:

<?php
    $searchVal = $_POST['username'];
    try {
        $dbh = new PDO("mysql:host=$hostname;dbname=$data", $username, $password);
        $sql = "SELECT * FROM users WHERE USERNAME = " . "'" . $searchVal .  "'";
        $stmt = $dbh->query($sql);
        $result = $stmt->fetch(PDO::FETCH_ASSOC);

        if($result>0) {
            $valid = "true";
        } else {
            $valid = "false";
        }

        $dbh = null;

        echo $value;
    }
    catch(PDOException $e) {
        echo $e->getMessage();
    }       

?>

?>

回答by pl71

This is a solution using a different plugin from here. For checking name availability using Ajax calls make following:

这是使用与此处不同的插件的解决方案。要使用 Ajax 调用检查名称可用性,请执行以下操作:

After downloading attach jquery.validationEngine.jsand your locale like:

下载附件后jquery.validationEngine.js,您的语言环境如下:

<script src="js/jquery.validationEngine-en.js" type="text/javascript" charset="utf-"></script>
<script src="js/jquery.validationEngine.js" type="text/javascript" charset="utf-8"></script>

Note, that enlocale is also compulsory to be included.

请注意,该en语言环境也必须包括在内。

Open and modify your language file, you have to point where is your phpfile which will check the database for name availability or to use default file name. So, find the following rows in jquery.validationEngine-en.jsin case you use English.

打开并修改您的语言文件,您必须指出您的php文件在哪里,该文件将检查数据库的名称可用性或使用默认文件名。因此,jquery.validationEngine-en.js如果您使用英语,请找到以下行。

 "ajaxUserCallPhp": {
    "url": "phpajax/ajaxValidateFieldUser.php",

Here you can change file name if you want like:

如果需要,您可以在此处更改文件名:

 "ajaxUserCallPhp": {
    "url": "my-file_which_will_check_db.php",

And your my-file_which_will_check_db.phpshould look like:

my-file_which_will_check_db.php应该看起来像:

<?
/* RECEIVE VALUE */
$validateValue=$_REQUEST['fieldValue'];
$validateId=$_REQUEST['fieldId'];

$validateError= "This username is already taken";
$validateSuccess= "This username is available";

/* RETURN VALUE */
$arrayToJs = array();
$arrayToJs[0] = $validateId;

$dbh = new PDO('mysql:host=localhost;dbname=test', $user, $pass); //Connect with your credentials
$stmt = $dbh->query("SELECT * From `users` WHERE `USERNAME` = '{$validateValue}'"); 
$dbh = null;                    // Disconnect

sleep(1); /*added because check is very fast and the label 'checking...' is not visible*/

if ($result = $stmt->fetch()) { 
$arrayToJs[1] = false;          // found user with that name
echo json_encode($arrayToJs);           
}
else {
$arrayToJs[1] = true;
echo json_encode($arrayToJs);       // that user name is free
}
?>

Finally, your HTML markup should look like:

最后,您的 HTML 标记应如下所示:

<input type="text" name="user_name" id="user_name" class="validate[required],custom[onlyLetterNumber],maxSize[20],ajax[ajaxUserCallPhp] text-input" />

Note additional classattribute here.

注意class这里的附加属性。

And include following script:

并包括以下脚本:

<script>
  $(document).ready(function(){
  $("#register_form").validationEngine();
  });
</script>