I'm trying to create a simple like/unlike button which updates the database. The jQuery code is in an external file. The PHP variables are sent from the controller in Codeigniter.
When the page loads fresh, it correctly displays whether the currently-logged-in user is able to Like or Unlike the user they are viewing. If they click once, everything works as it should - the button changes between Like / Unlike, the number of likes increases or decreases and the database is updated. On clicking a second time, it reloads the whole page but doesn't update the database - how do I stop it refreshing + make it update without page reload?
The PHP:
<div id="like_button">
<p><a href=""><span id="like_unlike" class="link"><?php if($already_liked){echo "Unlike";}else{echo"Like";}?></span></a> (<span id="number_of_likes"><?php echo $number_of_likes; ?></span>)</p>
<span id="liked_unliked_user_id" style="display:none"><?php echo $liked_unliked_user_id; ?></span>
<span id="liking_unliking_user_id" style="display:none"><?php echo $liking_unliking_user_id; ?></span>
</div>
The jQuery:
$( function() {
$( '#like_button a' ).click( function( e ) {
var thisrecord = $( this ).closest( "div" );
var liking_unliking_user_id = parseInt( thisrecord.find( "span#liking_unliking_user_id" ).html() );
var liked_unliked_user_id = parseInt( thisrecord.find( "span#liked_unliked_user_id" ).html() );
var like_unlike = thisrecord.find( "#like_unlike" ).html();
if (like_unlike == 'Like')
{
$( this ).replaceWith( '<a href=""><span id="like_unlike" class="link">Unlike</span></a>' );
var likes = parseInt( thisrecord.find( "span#number_of_likes" ).html() ) + 1;
thisrecord.find( "span#number_of_likes" ).html( likes );
$.post( base_url+"/controller/function/" + liked_unliked_user_id + "/" + liking_unliking_user_id );
}
else
{
$( this ).replaceWith( '<a href=""><span id="like_unlike" class="link">Like</span></a>' );
var likes = parseInt( thisrecord.find( "span#number_of_likes" ).html() ) - 1;
thisrecord.find( "span#number_of_likes" ).html( likes );
$.post( base_url+"/controller/function/" + liked_unliked_user_id + "/" + liking_unliking_user_id );
}
e.preventDefault();
});
});