On my site i would like the give the ability for users to like profile pages.
So my logic is this.
I have a database table named user_likes, this contains 3 rows, id, user_id, liked_by.
The actual profile page has a like button on it with a class like.
When the user clicks on it in inserts the data in to the user likes table and changes the button text to unlike and the class to unlike too with ajax.
And this is the part where im stuck.
So the profile has a has many relation likes, i can count the likes recived, but im stuck at that part how to keep the button unliked after page refresh.
Because my logic was this (but its a fail).
onclick the button, data insert with ajax, button change with ajax, grab the liked by id and if that equals to the logged in users id keep the button unliked.
But since it returns a list of array i cant do that.
So i dont want to anybody code it for me, i would just like a hint for this if its not a big request.
When loading the user's profile, take the current user's id and the id of the profile being viewing and search your user_likes table for a match to both. If a match is found, display the unlike button, if not, display the like button. No need to use ajax to detect which button to display if you're refreshing the page.
First thank you for your answer and sorry for the stupid question again. I tried what you say, maybe im doin somthing really wrong os here is a code logic what i used
if(logged in user id == liked by) {
show button unlike
} else {
show button like
}
but the problem is that this way i get the button repeat as many likes he got.
So really sorry for beeing stupid but could you sketch a small logic?
Sure. Logic wise, you could do something like this:
query = Select from user_likes table where liked_by = <logged in user> AND user_id = <profile being viewed>
if (query returns a row)
show button unlike
else
show button like
What you're doing is querying the user_likes table for a row that contains the logged in user as the person who liked a profile, and the profile being viewed as the profile that got liked. If the query returns a row, that means the logged in user already liked the profile he/she is viewing.
If you use only the logged in user id in your query, then you will get an array of the profiles that person has liked. If you use only the id of the profile being used, you will get an array of the people who have liked that profile.