这里当通过ajax调用likes()函数时,函数会在不刷新页面的情况下正确执行,但在视图中用户的喜欢保持不变。刷新页面时,会显示更新的喜欢值。我希望在不刷新页面的情况下也应该显示更新。
before refresh, but likes() function executed
控制器:
public function likes()
{
if(!$this->session->userdata('logged_in_user'))
{
$this->session->set_flashdata('like','Please login to like.');
redirect('login');
}
$user_id = $this->input->post('user_id');
$events_id = $this->input->post('events_id');
// $permalink = $this->input->post('permalink');
$data = array(
'user_id' => $this->input->post('user_id'),
'events_id' => $this->input->post('events_id'),
'likes' => 1
);
$check_likes = $this->events_model->check_likes($user_id,$events_id);
if(empty($check_likes))
{
$this->events_model->create_likes($data);
// redirect('events/view/' .$permalink);
}
else
{
if($check_likes['likes'] == 1)
{
$this->events_model->unlike($events_id,$user_id);
// redirect('events/view/' .$permalink);
}
else
{
$this->events_model->update_like($events_id,$user_id);
// redirect('events/view/' .$permalink);
}
}
}
型号:
public function create_likes($data){
return $this->db->insert('flix_likes',$data);
}
public function get_likes($events_id)
{
$this->db->select('flix_profiles.name,flix_likes.*');
$this->db->from('flix_profiles');
$this->db->join('flix_likes','flix_likes.user_id = flix_profiles.user_id');
$this->db->where('flix_likes.events_id',$events_id);
$query = $this->db->get();
return $query->result_array();
}
查看:
<form id="form">
<?php
$cnt=0;
foreach ($likes as $value)
{
$cnt += $value['likes'];
} ?>
<input type="hidden" id="user_id" name="user_id" value="<?php echo $this->session->userdata('id'); ?>">
<input type="hidden" id="events_id" name="events_id" value="<?php echo $events['events_id']; ?>">
<input type="hidden" id="permalink" name="permalink" value="<?php echo $events['permalink']; ?>">
<button class="fa fa-thumbs-up fa-2x"></button> <b style="font-size:'20';"><?php if(!empty($likes)) { echo $cnt." Likes."; } ?></b>
</form>
的Jquery / AJAX:
$(function () {
$("#form").submit(function(e){
var user_id = $('#user_id').val();
var events_id = $('#events_id').val();
var permalink = $('#permalink').val();
$.ajax({
type:'POST',
url:'<?php echo base_url('events/likes'); ?>',
data:{'user_id':user_id,'events_id':events_id,},
success:function(data){
console.log('success');
}
});
return false;
});
});
答案 0 :(得分:0)
首先停止表单提交,然后在ajax成功后反映值。
$(function () {
$("#form").submit(function(e){
e.preventDefault(); //-------------------
var user_id = $('#user_id').val();
var events_id = $('#events_id').val();
var permalink = $('#permalink').val();
$.ajax({
type:'POST',
url:'<?php echo base_url('events/likes'); ?>',
data:{'user_id':user_id,'events_id':events_id,},
success:function(data){
var jsonData = JSON.parse(data); //--------
$('#likes').text(jsonData.likes);
console.log('success');
}
});
return false;
});
});