检查DB jquery中是否已存在输入数据

时间:2013-11-17 09:54:10

标签: php jquery mysql

我有一个在mysql数据库中添加设备名称和设备ID的表单。我编写了一个jquery脚本,用于检查设备ID是否已经在db中。如果存在,它将返回false。我有以下代码 -

<script src="http://code.jquery.com/jquery-latest.js"></script>
                                        <script type="text/javascript">
                                        $(document).ready(function(){ //newly added 
                                        $('#Submit').click(function() {alert('in');
                                            var checkID = $('#device_id').val(); // assuming this is a input text field
                                            $.post('includes/checkid.php', {'device_id' : checkID}, function(data) {
                                                if(data=='exist') alert("already exists"); return false;
                                                else $('#add_dev').submit();
                                            });
                                        });});
                                        </script>


<form method="post" action="includes/process_add.php" name = "add_dev" id = "add_dev">
                    <tr><td width="150">Device ID</td><td>:<input type="text" name="device_id" id= "device_id"></td></tr>
                    <tr><td>Device Name</td><td>:<input type="text" name="device_name"></td></tr>
                    <tr><td></td><td><br><input type="submit" name="submit" id= "submit" value="Add device"></td></tr>
                    </form> 

和checkid.php是 -

<?php
include("connection.php");
$id = $_POST['device_id'];
$sql = mysql_query("SELECT device_id FROM devices WHERE device_id = '$id'");

if (mysql_num_rows($sql) > 0) {
    echo "exist";
}else echo 'notexist';
?>

它不起作用..

1 个答案:

答案 0 :(得分:0)

Ajax是异步的,在ajax成功回调之外返回false:

$(document).ready(function () { //newly added 
    $('#submit').click(function () {        
        alert('in');
        var checkID = $('#device_id').val(); // assuming this is a input text field
        $.post('includes/checkid.php', {
            'device_id': checkID
        }, function (data) {
            if (data == 'exist') alert("already exists");            
            else $('#add_dev').submit();
        });
        return false;
    });
});