I have a for loop that creates a number of forms on the page. I want to be able to submit these forms to another page without refresh using AJAX, however no matter which form I submit it only ever shows the value for the very last form.
HTML code
{% for post in post_list %}
<form class = "f_form" id="f_form" name = "myForm" method="POST">
{% csrf_token %}
{{ form.as_p }}
<button type="submit" class="add">Submit</button>
</form>
{% endfor %}
Jquery
<script type="text/javascript">
$(document).ready(function(){
$(document).on('click','.add',function (event) {
event.preventDefault();
var element = $(this);
$.ajax({
url: '{% url "webscraper-favorited" %}',
method: 'post',
data:element.parent('.f_form').serialize(),
success: function(data){
$('#message').html(data);
}
});
return false;
});
});
</script>
views.py
def favorited(request):
if request.method == 'POST':
favorited = request.POST.get('favorited')
favorites.append(favorited)
print(favorited)
context = {
'favorites' : favorites,
}
return render(request, 'webscraper/favorited.html', context)
Right now the script is outside of the for loop but I previously tried putting it in the for loop as well. Instead of binding the script to the submit button I also tried binding it to the form id. That yielded the same result from my attempts.
You are using the same
idfor multiple forms in your loop. HTMLidattributes must be unique within a document. When you use$('#f_form')in your jQuery code, it only selects the first form with thatid.Modify your HTML and jQuery code to use class selectors instead of
idfor the forms. Here's an updated version:HTML code:
jQuery code: