Ajax using Rails
- by Steve
Hi,
I have a favourite and un-favourite functionality in my application and I am using jQuery. This functionality works partially. The page gets loaded, and when I click the 'favourite' button(it is inside add_favourite_div element), it sends a XHR request and the post is set as favourite. Then a new div called "remove_favourite_div" replaces its place.Now when I click the remove favourite(which is part of remove_favourite_div), it sends a normal http request inside of xhr.
The structure when the page gets loaded first time
<div id="favourite">
<div id="add_favourite_div">
<form method="post" id="add_favourite" action="/viewpost/add_favourite">
<div style="margin: 0pt; padding: 0pt; display: inline;">
<input type="hidden"
value="w873BgYHLxQmadUalzMRUC+1ql4AtP3U7f78dT8x9ho="
name="authenticity_token">
</div>
<input type="hidden" value="3" name="Favourite[post_id]"
id="Favourite_place_id">
<input type="hidden" value="2" name="Favourite[user_id]" id="Favourite_user_id">
<input type="submit" value="Favourite" name="commit"><br>
</form>
</div>
</div>
DOM after clicking on the unfavourite button
<div id="favourite">
<div id="remove_favourite_div">
<form method="post" id="remove_favourite" action="/viewpost/remove_favourite">
<div style="margin: 0pt; padding: 0pt; display: inline;">
<input type="hidden" value="w873BgYHLxQmadUalzMRUC+1ql4AtP3U7f78dT8x9ho="
name="authenticity_token">
</div>
<input type="hidden" value="3" name="Favourite[post_id]" id="Favourite_place_id">
<input type="hidden" value="2" name="Favourite[user_id]" id="Favourite_user_id">
<input type="submit" value="UnFavourite" name="commit"><br>
</form>
</div>
</div>
In my application.js, I have two functions to trigger the xhr request
$("#add_favourite").submit(function(){
alert("add favourite");
action = $(this).attr("action")
$.post(action,$(this).serialize(),null,"script");
return false;
});
$("#remove_favourite").submit(function(){
alert("remove favourite");
action = $(this).attr("action");
$.post(action,$(this).serialize(),null,"script");
return false;
});
Here, when the post is initially not a favourite, favourite button is displayed and when i clicked on the button, $("#add_favourite").submit gets called and unfavourite form is displayed correctly, but now when I click on the un-favourite button, $("#remove_favourite").submit does not get called.
The whole scenario is true in both ways, I mean favourite-Unfavourite and Unfavourite-favourite
Can someone please help me to solve this
Thanks