使用html重复记录验证

时间:2015-02-18 07:00:53

标签: php mysql unique primary-key

购买表有两个字段purchase_id,其中主键和purchase_order_no是唯一键。我有一个简单的HTML表单。并且有一个字段.i.e purchase_order_no。我想使用jquery或javascript为purchase_order_no字段设置唯一的id验证。那我该怎么做?

2 个答案:

答案 0 :(得分:1)

如果这是关于检查数据库中是否唯一,您可能想要使用jQuery $ ajax方法:获取键入的id,将其发送到您检查/验证它的PHP文件,然后在表单中显示结果相同的$ ajax回调方法...

看看this answer ...

您的HTML表单:

<form id="foo">
    <label for="bar">The Order No: </label>
    <input id="purchase_order_no" name="purchase_order_no" type="text" value="" />
    <input type="submit" value="Check Number" />
    <p id="result"></p>
</form>

然后你的javascript:

$(document).ready(function(){
    $("#foo").submit(function(event) {
        $("#foo").attr("disabled","disabled"); // better to disable the submit button during the ajax call...
        $.ajax({
            url: "tester.php",
            type: "post",
            data: "number_to_test=".$("#purchase_order_no").val(),
            success: function(data) {
                if (data == 'ok')
                   $("#result").html('The Order number is valid');
                else if (data == 'no_ok')
                   $("#result").html('The Order number is not valid');
                else 
                   $("#result").html('Error in the returned value');
            },
            error:function() {
                $("#result").html('There is an error somewhere');
            }
        });
    });
});

然后在你的文件tester.php中:

<?php
    $numberToTest = $_POST["number_to_test"];
    /* here you test what you want, check the database, whatever */
    if ($numberToTest == "123") echo "ok";
    else echo "not_ok";
?>

答案 1 :(得分:0)

您可以使用jQuery的unique()函数检查值:http://api.jquery.com/jquery.unique/