I have a small site where I would like to give the ability to users to like each profile with ajax.
So the logic is this, if the use clicks on the like it inserts, but if the person already liked and that's found in the database delete the record this would be the unlike function.
So the controller looks like this.
public function action_like()
{
$response = Response::forge();
$like = Model_Like::forge();
$like->user_id = Input::post('user_id');
$like->liked_by = Session::get('sentry_user');
// find if the user already liked
$row = Model_Like::find(array($like->user_id, $like->liked_by));
//if liked remove from database
if($row):
$response->body(json_encode(array(
'status' => 'no',
)));
$row->delete();
else:
$response->body(json_encode(array(
'status' => 'yes',
)));
$like->save();
endif;
return $response;
}
javascript
$('button.like').on('click', function(){
var likeId = $(this).data('like')
valPlus = parseInt($('.like-total').text()) + 1;;
$.ajax({
type: "POST",
url: site_url + 'profile/like/',
data: {user_id: likeId},
dataType: "json",
context: this,
//async: false,
beforeSend: function(data) {
$(this).attr('disabled', 'disabled');
},
success: function(data) {
console.debug(data);
if(data.status == "yes") {
$('.like-total').text(valPlus);
}
},
complete: function(data) {
$(this).removeAttr('disabled', 'disabled');
}
})
});
So the problem is that the $row
always retunrs null
, so it is not locating the two id's and always inserts.
Could please someone give me a hint what I am missing?
I think you have an error in your "Where". Can you try with this?
$row = Model_Like::find()->where(array(
array('user_id', $like->user_id),
array('liked_id', $like->liked_by)
));
With your "Where" you where searching for the records with ids "$like->user_id" and "$like->liked_by", not for a single row with both of them.