1๐
-
You are creating an HTML element with id
fav
inside a loop. This will result in incorrect HTML with several elements having the same id, if the loop has more than one iteration. -
You lookup
$('#fav')
instead of the element that triggered the submit event.
=> Remove id='fav'
from your markup. (You can add an ID like id='fav-{{item.id}}
if you want but it is not necessary.
=> Change your JS:
<script type="text/javascript">
var csrftoken = $("input[name=csrfmiddlewaretoken]").val();
$(document).on('submit', '#add_favorite_form',function(e){
e.preventDefault();
var itemId= $(e.target).data('itemid'); // jquery +1.4.3 or attr()
$.ajax({
type: "POST",
url: "/items/favorites/",
data: {
id: itemId,
csrfmiddlewaretoken: csrftoken
},
success: function(){
alert("Added favorite " + itemId);
}
});
});
</script>
EDIT:
A simpler way to do it, is to use the form as such and just submit it via AJAX.
<form id="add_favorite_{{ item.id }}" class="add_favorite_form" method="POST" action="{% url 'add-favorite' %}">
{% csrf_token %}
<input type="hidden" name="id" value="{{ item.id }}" />
<button id='fav' class='btn btn-primary' type="submit" value="Favorite">
Favorite
<span class="glyphicon glyphicon-thumbs-up"</span></a>
</form>
JS:
<script type="text/javascript">
var csrftoken = $("input[name=csrfmiddlewaretoken]").val();
$(document).on('submit', '.add_favorite_form',function(e) {
e.preventDefault();
e.stopPropagation();
var $form = $(this);
var url = $form.attr( "action" );
var thisId = $form.attr( "id" );
$.post(url, $form.serialize())
.done(function(data) {
alert("Added favorite " + thisId);
});
});
</script>
0๐
You have a couple things wrong, but the one that is causing you the issue is that $('#fav')
will only ever find the first element on the page with that id.
Youโll find it hard to adjust your current javascript since it relies on the page submission. You could change it around to just have the button use an onclick event.
You will just need to include the CSRF token still but there are lots of resources about how to do that.
<button onclick="favourite({{item.id}})" class='btn btn-primary' value="Favorite">
function favourite(id){
// Use the id passed to the method
}