Im trying to make a 'Follow' button but the returned data, which is the 'Unfollow' button, is not working.
$('.follow_button').click(function() {
//event.preventDefault();
var visitor_user_id = $('.follow_button').attr('id');
$('#link_visitor_follow').empty().append('<div id = "follow_jquery_btn"><img src = "css/images/ajax_follow.gif" width = "12" height = "12" /> Follow</div>');
$.post('/unime/user_follow.php', {'type':'follow_me', visitor_user_id:visitor_user_id}, function(data){
if(data){
$('#link_visitor_follow').empty().html(data);
}
});
return false;
});
$('.unfollow_button').click(function() {
//event.preventDefault();
var visitor_user_id = $('.unfollow_button').attr('id');
$('#link_visitor_unfollow').empty().append('<div id = "follow_jquery_btn"><img src = "css/images/ajax_follow.gif" width = "12" height = "12" /> Following</div>');
$.post('/unime/user_follow.php', {'type':'unfollow_me', visitor_user_id:visitor_user_id}, function(data){
if(data){
$('#link_visitor_unfollow').empty().html(data);
}
});
return false;
});
PHP returned data:
echo "<a class = 'unfollow_button' id = 'visitor_".$visitor_user_id."'><span id = 'check_mark'></span> Unfollow</a>";
When I click the Unfollow button, it is not working, although I have the code setup for it. There is nothing wrong with the PHP itself. Its not even calling Ajax when I click Unfollow.
You can only bind to elements that currently exist. If they do not, you need to delegate to the element that WILL exist.
Change:
$('.unfollow_button').click(function() {
To:
$('#link_visitor_follow').on('click', '.unfollow_button', function() {
And it will delegate clicks to the not yet existent element, the event will bubble up from unfollow button until it hits link_visitor_follow, which has an event bound, and since it came from unfollow button it will now call the event (if that makes sense).
Also, you will need to do the same thing for the follow button in case they follow, unfollow, then follow again.
Dave answer should be enough for your question but if you are using jQuery below version 1.7, you can try these;
$('.unfollow_button').live('click', function() {
//your code here
})