Reputation: 497
I have seen a few of these questions post on here but none of them are working for me. I have a favourite button that i would like my users to press to favourite things. The ajax request is working just fine and the favourite gets stored in the database but i can only use it once then i have to refresh the page to fav/unfav the item. The code for the button is:
<div id="fav-icon">
<?php
// Function checks if user has fav'd the item.
$isFav = favourite($user->id) ? 'un-fav' : 'fav';
?>
<i id="<?php echo $item->id; ?>" class="<?php echo $isFav; ?>"><span class="font-12 fa fa-heart"></span></i>
</div>
Jquery/Ajax
$('.fav').click(function(e){
var con = $(this).attr('id');
$.ajax({
url: 'fav.php',
type: 'POST',
async: true,
data:{
'fav' : con
},
success:function(){
$('#fav-icon').load(document.URL + ' #fav-icon');
}
});
});
$('.un-fav').click(function(e){
var con = $(this).attr('id');
$.ajax({
url: 'fav.php',
type: 'POST',
async: true,
data:{
'fav' : con
},
success:function(){
$('#fav-icon').load(document.URL + ' #fav-icon');
}
});
});
So this works but only once! I have tried a couple of different functions to try make this work including:
$('.fav').live('click', function(e) {
Can anyone tell me where i am going wrong and the correct method to get my button to work multiple times?
Upvotes: 0
Views: 141
Reputation: 8101
Use $(document).on()
click event
$(document).on('click','.fav', function(e) {
...
});
Upvotes: 2