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>