ajax php表单验证无效

时间:2014-03-13 05:16:41

标签: javascript php jquery ajax

我编写了一个php文件和jquery来从数据库中检索数据并验证文本字段模糊事件,以检查键入的值是否可用。以下是我的代码:

表格php:

<script>
        $("#catname").blur(function() {
            $.post("./scripts/checkavailability.php", {
                nameava: $("#catname").val(),
            }, function(data) {
                alert(data);
            });

            var setr = "<?php
                         include './scripts/checkavailability.php';
                         $dbava = getfromdb("name", "tbl_category");
                         $avams = check($txtval, $dbava, "$name");
                         echo $avams;
                         ?>";
            $("#jinx").html(setr);

        });
    </script>

checkavalilability.php:

<?php

if (isset($_POST['nameava'])) {
$txtval = mysql_real_escape_string($_POST['nameava']);
}


function getfromdb($field, $table) {
$avres = mysql_query("SELECT `" . $field . "` FROM `" . $table . "`");
return $avres;
}

function check($curval, $qres, $s_field) {
while ($a_row = mysql_fetch_array($qres)) {
    $dbval = $a_row[$s_field];

    if ($curval == $dbval) {
        return "This value is taken";
        break;
    } else {
        return "This value is available";
    }
}
}

?>

注意:catname是textfield id,jinx是div id。

1 个答案:

答案 0 :(得分:2)

我认为你正在尝试这样的事情:

jQuery的:

<script>
    $("#catname").blur(function() {
        $.post("./scripts/checkavailability.php", {
            nameava: $("#catname").val(),
        }, function(data) {
            alert(data);
            $("#jinx").html(data);
        });

    });
</script>

PHP:

<?php

function getfromdb($field, $table) {
    $avres = mysql_query("SELECT `" . $field . "` FROM `" . $table . "`");
    return $avres;
}

function check($curval, $qres, $s_field) {
    while ($a_row = mysql_fetch_array($qres)) {
        $dbval = $a_row[$s_field];

        if ($curval == $dbval) {
            return "This value is taken";
            //break;
        } else {
            return "This value is available";
        }
    }
}

if (isset($_POST['nameava'])) {
    $txtval = mysql_real_escape_string($_POST['nameava']);
    $dbava = getfromdb("name", "tbl_category");
    $avams = check($txtval, $dbava, "name");
    echo $avams;
}
exit();
?>