So I have a project where I'm trying to allow users to favorite a listing. I am trying to use a button and jquery to accomplish this.
I have the button setup as follows:
<button type="submit" name="fav" id="fav" data-action="add" data-listing-id="40" class="btn btn-default btn-xs"><i class="fa fa-star-o pull-left notfav"></i> Add to Favorites</button>
When they click on the button I want to use AJAX to call a php script and pass it the listing ID and the action. Then it processes the favorite request and then returns success or fail. then if it was successful I want to change the action attribute to "delete" (if I just added it as a favorite) and change the HTML to show "My favorite" -- so they know the favorite was recorded.
Here is the JS I have currently:
jQuery(document).ready(function($) {
$("#fav").click(function(){
var action = $(this).data("action");
var id = $(this).data("listing-id");
var dataString = 'id='+id+'&action='+action;
$.ajax({
type: "POST",
url: "/favsubmit.php",
data: dataString,
cache: false,
success: function(result){
if(result=="login"){
window.location.href = "/user_login.php";
}else if(result=="success"){
if(action=="add"){
$("#fav").html('<i class="fa fa-star pull-left fav"></i> My Favorite').button("refresh");
$("#fav").attr("data-action","delete");
}else if(action=="delete"){
$("#fav").html('<i class="fa fa-star-o pull-left notfav"></i> Add to Favorites').button("refresh");
$("#fav").attr("data-action","add");
}
} else if (result=="fail"){
console.log(result);
}
}
});
});
});
Now...The issue is the above HTML and JS works on the first click. But then on subsequent clicks its not picking up the changed data-action value. So if it wasn't a favorite and I click the button, it changes it to "My favorite" and the action to "delete" but when I click the button again, it tries to add the favorite again. it doesnt see the new action value of delete?
Can anyone spot my issue??
Thanks!!