如标题所述。我使用JQuery和Validate插件来验证表单中的用户输入。
我正在尝试实现对表中重复值的检查。
为此,我使用以下代码:
$().ready(function(){
//alert('JQuery Functioning');
$("#cat_name").change(function()
{
var cat_name = $("#cat_name").val();
$.ajax({
type:"POST",
url:"ws/cat_duplicate.php",
data:"cat_name="+cat_name,
cache: false,
success: function(html)
{
//alert(html);
if(html == 1)
{
$("#duplicate").html("<br/>Duplicate category Found. Please, Enter Unique Category Name");
$("#add_rec").attr("disabled",true);
}
else
{
$("#duplicate").html("");
$("#add_rec").attr("disabled",false);
}
}
}); //$.ajax({
}); //$("#cat_name").change(function()
$("#frmAddCategory").validate({
rules: {
cat_name: "required"
}, //rules: {
messages: {
cat_name: "<br />Please provide Category Name here"
} //messages: {
}); //$("#frmAddCategory").validate
});
这是HTML部分:
<h2>Category Edit</h2>
<form id="frmAddCategory" name="frmAddCategory" method="post" action="">
<table width="25%" border="0" align="center" cellpadding="0" cellspacing="0">
<tr>
<td>ID</td>
<td>Auto Generated</td>
</tr>
<tr>
<td>Category Name</td>
<td><input name="cat_name" type="text" id="cat_name" value="" maxlength="60" /><span id="duplicate"></span></td>
</tr>
<tr>
<td> </td>
<td> </td>
</tr>
<tr align="center" valign="middle">
<td colspan="2"><input type="submit" name="add_rec" id="add_rec" value="Add" />
<a href="cat_list.php">Cancel</a></td>
</tr>
</table>
</form>
我调用的PHP代码是:
<?php
if(isset($_POST['cat_name']))
{
require_once('../conn/blog.php');
mysqli_select_db($blog, $database_blog);
$cat_name = $_POST['cat_name'];
$query = "SELECT cat_name FROM category WHERE cat_name = '$cat_name'";
$query_retrived = mysqli_query($blog, $query) or die("Error:".mysqli_error($blog));
$rows = mysqli_fetch_assoc($query_retrived);
$result = mysqli_num_rows($query_retrived);
if ($result>0)
{
echo '1';
}
else
{
echo '0';
}
mysqli_free_result($query_retrived);
}
?>
但在这段代码中,我必须启用或禁用提交按钮。相反,我希望Validate插件能够处理重复值的检查。
我们该怎么做?
TIA-
您可以尝试"远程";检查数据库中是否存在相同类别的方法
$( "#frmAddCategory" ).validate({
rules: {
cat_name: {
required: true,
remote: {
url:"ws/cat_duplicate.php",
type: "post",
async: false,
data: {
cat_name: function() {
return $( "#cat_name" ).val();
}
}
}
}
},
messages: {
cat_name: {
required:"Please provide Category Name here",
remote:"This Category alredy exist"
},
}
});
在PHP代码中,你可能需要像一样返回字符串"true"或"false">
<?php
if(isset($_POST['cat_name']))
{
require_once('../conn/blog.php');
mysqli_select_db($blog, $database_blog);
$cat_name = $_POST['cat_name'];
$query = "SELECT cat_name FROM category WHERE cat_name = '$cat_name'";
$query_retrived = mysqli_query($blog, $query) or die("Error:".mysqli_error($blog));
$rows = mysqli_fetch_assoc($query_retrived);
$result = mysqli_num_rows($query_retrived);
if ($result>0)
{
echo 'true';
}
else
{
echo 'false';
}
mysqli_free_result($query_retrived);
}
?>