Reputation: 300
I have been working in app that contains a like button in profiles I have stopped here and don't know how to complete it!! What is missed here to make it work? can you help ?
Ajax
<script type="text/javascript">
$(document).ready(function() {
$("#likebtn").click(function(e){
$.post(
function(data)
{
if (data.st == 0)
{
$('#likedata').html(data.msg);
}
else if (data.st == 1)
{
<?php echo $numlikes+1; ?>
}
},
'json'
);
return false;
});
});
</script>
Button in the View
<p> <input type="button" id="likebtn" class="btn btn-default btn-lg"> Likes</p>
<span class="label label-default" id="Likes"><?php echo $numlikes; ?></span>
<div id="likedata"></div>
on construct function of the controller
function __construct() {
parent::__construct();
$prifile_id = $this->uri->segment(2, 9);
$user_id = ($this->session->userdata['logged_in']['user_id']);
}
Controller function to add like
public function addlike()
{
$checklike = $this->$this->profiles_model->checklike($user_id,$profile_id);
if ($checklike == FALSE)
{
$this->profiles_model->addlike($user_id,$prifile_id);
$output= array('st'=>1);
echo json_encode($output);
}
else {
$output = array('st'=>0, 'msg' => "you already likes this profile");
echo json_encode($output);
}
}
Thanks in advance :)
Upvotes: 0
Views: 643
Reputation: 2643
You want to increment count, but it is good to get updated count from server. Following is some javascript changes.
<script>
$.post(
"<?php echo site_url('profiles/addlike'); ?>",
function(data)
{
if (data.st == 0)
{
$('#likedata').html(data.msg);
}
else if (data.st == 1)
{
$("#Likes").text(st.numLikes);
}
},
'json'
);
return false;
});
});
</script>
Now, Return updated numofLikes from server too.
public function addlike()
{
$checklike = $this->$this->profiles_model->checklike($user_id,$profile_id);
if ($checklike == FALSE)
{
// Update this model method, so that it returns updated like count.
$numLikes = $this->profiles_model->addlike($user_id,$prifile_id);
$output= array('st'=>1,'numLikes'=>$numLikes);
echo json_encode($output);
}
else {
$output = array('st'=>0, 'msg' => "you already likes this profile");
echo json_encode($output);
}
}
Upvotes: 1