我正在发送一个ajax请求,它也返回成功消息,但数据没有插入。基本上它是一个链接,当我点击链接时,ajax会向控制器发送一个请求,在数据库中,它会将之前的值增加1。我试过很多次,但都失败了。这是一个联合签署人项目。如果你能帮忙,我们将不胜感激。
Ajax File :
$(document).ready(function(){
$("#like").click(function(e){
e.preventDefault(); // <------this will restrict the page refresh
var post_id = $(this).prop('rel');
$.ajax({
url: "http://localhost/ci_website/index.php/site/add_like",
type: 'POST',
data : post_id,
dataType: 'json',
success: function(res) {
if (res.success) {
alert(res.msg);
} else {
alert(res.msg);
}
}
});
return false;
});
});
View File :
<a id="like" class="like_btn" rel="<?php echo $blog['blog_id'];?>" href="<?php echo site_url('site/add_like') . '/' . $blog['blog_id'];?>">Like</a>
控制器文件:
public function add_like()
{
header('Content-Type: application/json');
if ($this->input->is_ajax_request()) {
$post_id = $this->uri->segment(3);
$this->db->set('post_like', '`post_like` + 1', FALSE);
$this->db->where('blog_id', $post_id);
$add_post_view = $this->db->update('wb_blog');
if ($add_post_view) {
die(json_encode(array('success' => true, 'msg' => 'Your Like has been sent successfully.')));
} else die(json_encode(array('success' => false, 'msg' => 'Something bad happened!!! Please, try again.')));
}
}
更新
使用检查
if ($this->db->_error_message()) {
return FALSE; // Or do whatever you gotta do here to raise an error
} else {
return $this->db->affected_rows();
}`
您没有调用函数,只是加载函数,由于文件加载成功,因此返回true。定义完函数后,试着调用它,看看它是否有效。
url: "http://localhost/ci_website/index.php/site/add_like/"+post_id,
我在链接后添加了"post_id"。这很好。我没有定义表的行将受到影响的确切id。