1

I am trying to create a Follow/Unfollow button that can function both ways repetitively without needing to refresh the page. It functions perfectly in the sense that if I click "Follow", it adds the follow data to the database via my PHP file and then shows the "Unfollow" button in it's place and vice versa, this is all fine. However, once it shows the opposite button, I cannot click it until I refresh the page? How can I make it so that each function will work for each button simultaneously in the way I intend?

jQuery/AJAX:

<script>
$(function() {
$(".followUser").click(function() 
{
var userid = $(this).attr("id");
var dataString = 'userid='+ userid ;
var parent = $(this);

$("#followButton").fadeOut(300);
$.ajax({
type: "POST",
url: "follow.php",
data: dataString,
cache: false,

success: function(html)
{
$("#followButton").html('<button id="' +userid '" name="unfollow" class="btn btn-danger unfollowUser">Unfollow</button>');
$("#followButton").fadeIn(300);

} 
});
return false;
 });
});

$(function() {
$(".unfollowUser").click(function() 
{
var userid = $(this).attr("id");
var dataString = 'userid='+ userid ;
var parent = $(this);

$("#followButton").fadeOut(300);
$.ajax({
type: "POST",
url: "unfollow.php",
data: dataString,
cache: false,

success: function(html)
{
$("#followButton").html('<button id="' +userid '" name="follow" class="btn btn-info followUser">Follow</button>');
$("#followButton").fadeIn(300);

} 
});
return false;
 });
});
</script>

HTML:

<div id="followButton">

    //if isn't following
    <button id="1" name="follow" class="btn btn-info followUser">Follow</button>

    //if is following
    <button id="1" name="unfollow" class="btn btn-danger unfollowUser">Unfollow</button>

</div>
Engine
  • 89
  • 1
  • 4
  • 14

2 Answers2

2

On document load you set button click functions on buttons generated by php script.

But on ajax success you are replacing content of #followButton with new button. So previous .click is lost.

You have several choices:

  1. Add onClick event after creating new button
  2. Simple use fadeIn / fadeOut on your follow/unfollow buttons
Majky
  • 1,943
  • 1
  • 18
  • 30
  • Is there no way of resetting the functions to work for the newly added buttons? – Engine Jul 23 '13 at 10:52
  • 1
    Here is what you are looking for http://stackoverflow.com/questions/1359018/in-jquery-how-to-attach-events-to-dynamic-html-elements – Majky Jul 23 '13 at 10:56
0
Use show hide on clicking on like button show unlike and hide like and vice-versa. then it will work fine

$("#hide").click(function(){
  $("tagname").hide();
});

$("#show").click(function(){
  $("tagname").show();
});

hope it will help you