I am building up a Like/Unlike system, I have a button what has a class like, if i click it data is inserted in the database, and the class is changed to unlike.
And unlike suppose to pull another ajax call what removes the actual like but its not working, when the class changed it preforms what like class suppose to do, and it only works if i refresh the page.
php code
<div class="btn-group pull-right">
<?php
$like = '<button class="btn btn-primary btn-small like" data-like="'.$user->id.'">
<i class="icon-thumbs-up icon-white"></i> Like
</button>';
foreach ($user->likes as $likes) {
if($likes['liked_by'] == Session::get('sentry_user')) {
$like = '<button class="btn btn-primary btn-small unlike" data-like="'.$user->id.'">
<i class="icon-thumbs-down icon-white"></i> Unlike
</button>';
break 1;
}
}
echo $like;
?>
</div>
jquery
$('button.like').bind('click', function(){
var likeId = $(this).data('like');
$.ajax({
url: siteUrl + 'profile/like',
type: "post",
data: {user_id: likeId},
dataType: "json",
context: this,
beforeSend: function()
{
$(this).addClass('disabled');
},
success: function(data)
{
if(data.status == "like") {
$(this).removeClass('like')
.addClass('unlike')
.append()
.html('<i class="icon-thumbs-down icon-white"></i> Unlike');
}
},
complete: function()
{
$(this).removeClass('disabled');
}
});
});
$('button.unlike').bind('click', function(){
var likeId = $(this).data('like');
alert('you are about to unlike');
})
just made the unlike alert for an example to test it befoe I make the ajax call with it.
So cloud someone give me a hint?
i’ve done something similar on my app, i used this logic:
html:
js:
also you can refactoring this example for using just 1 ajax call, you will have less code