尝试使用Ajax和Jquery检查唯一类别标题。
jQuery和Ajax内容
<script>
$(document).ready(function(){
$('#category_title').change(function(){
var category_title = $(this).val();
$.ajax ({
url : "ajax_calls.php",
method : "POST",
data : {category_title :category_title },
dataType: "text",
success:function(html)
{
$('#availablity').html(html);
}
});
});
</script>
ajax_call.php
<?php
include 'commands.php';
if (isset($_POST['category_title'])) {
$category_title = $_POST['category_title'];
$obj= new commands();
$result= $obj->check_category_title($category_title);
if (empty($result)) {
echo "<span class='status-available' style='color:green;'> Username Available.</span>";
} else {
echo "<span class='status-not-available' style='color:red;'>Category Already Exist</span>";
}
}
?>
HTML内容
<form action="" method="post" id="my_form" enctype="multipart/form-data">
<div class="form-group">
<label class="tags">Category Title</label>
<input type="text" name="category_title" class="form-control" id="category_title"><span id="availablity"></span>
<p class="errorMsg"><?php if(isset($errorTitle) && $errorTitle== 1){echo "Field Required" ;} ?> </p>
</div>
</form>
MySQLi内容
function check_category_title($category_title){
$stmt = $this->con->prepare("SELECT category_title FROM `nm_category` WHERE category_title='$category_title'");
$stmt->execute();
$result=$stmt->fetchAll(PDO::FETCH_ASSOC);
return $result;
}
如果表中已经存在该类别,我想阻止用户提交,否则允许用户提交
答案 0 :(得分:1)
在您的php代码中进行如下更改:
if (empty($result)) {
echo "<span class='status-available' style='color:green;'> Username Available.</span>";
//show submit button if no data found
echo "<input type='submit' value='submit'>";
} else {
echo "<span class='status-not-available' style='color:red;'>Category Already Exist</span>";
//disabled button to prevent submit if category exist
echo "<input type='submit' value='submit' disabled='disabled'>";
}