我正在尝试使用AJAX检查CodeIgniter网站的数据库中是否存在值。我已经写了以下代码:
<input id="username" name="pincode" type="text" class="form-control" placeholder="Enter Pincode">
<input id="prodid" name="prodid" value="<?php echo $prodid;?>" type="hidden">
<button type="button" onclick="check_if_exists();" class="btn btn-primary">Check</button>
function check_if_exists() {
var username = $("#username").val();
var prodid = $("#prodid").val();
$.ajax({
type: "post",
url: "<?php echo base_url(); ?>index.php/homecontroller/filename_exists",
data: {
username: username,
prodid: prodid
},
success: function(response) {
if (response == true) {
$('#msg').html('<span style="color: green;">' + msg + "</span>");
} else {
$('#msg').html('<span style="color:red;">Delivery Not Available at ' + username + '</span>');
}
}
});
}
function filename_exists()
{
$username = $this->input->post('pincode');
$prodid = $this->input->post('prodid');
$exists = $this->product->filename_exists($prodid);
if ($exists) {
return true;
} else {
return false;
}
}
function filename_exists($prodid)
{
$this->db->select('*');
$this->db->where('id', $prodid);
$this->db->from('product');
$query = $this->db->get();
$result = $query->result_array();
return $result;
}
我只收到一条消息,即即使该值在数据库中,该值也不存在。
- 您使用的是AJAX而不是表单提交方法,因此在后端post()方法不起作用
- 要在php中从服务器传输值,一种方法是echo,但这里的return是错误的。请这样重写代码查看
function check_if_exists() {
var username = $("#username").val();
var prodid = $("#prodid").val();
var transfer = [username,prodid];
$.ajax({
type: "post",
url: "<?php echo base_url(); ?>index.php/homecontroller/filename_exists",
data: {result: JSON.stringify(transfer)},
success: function(response) {
if (response) {
$('#msg').html('<span style="color: green;">' + msg + "</span>");
} else {
$('#msg').html('<span style="color:red;">Delivery Not Available at ' + username + '</span>');
}
}
});
}
控制器
function filename_exists()
{
$post = json_decode($_POST['result']);
$username = $post[0];
$prodid = $post[1];
$exists = $this->product->filename_exists($prodid);
echo $exists;
}
模态
function filename_exists($prodid)
{
$this->db->select('id');
$this->db->where('id', $prodid);
$this->db->from('product');
$query = $this->db->get();
if($query->num_rows()) return true;
}
enter code here