AJAX is only getting data from last form in loop (Django)

29 Views Asked by At

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.

1

There are 1 best solutions below

0
godd0t On

You are using the same id for multiple forms in your loop. HTML id attributes must be unique within a document. When you use $('#f_form') in your jQuery code, it only selects the first form with that id.

Modify your HTML and jQuery code to use class selectors instead of id for the forms. Here's an updated version:

HTML code:

{% for post in post_list %}
    <form class="f_form" name="myForm" method="POST">
        {% csrf_token %}
        {{ form.as_p }}
        <button type="submit" class="add">Submit</button>
    </form>
{% endfor %}

jQuery code:

<script type="text/javascript">
    $(document).ready(function(){
        $(document).on('submit', '.f_form', function(event) {
            event.preventDefault();
            var form = $(this);

            $.ajax({
                url: '{% url "webscraper-favorited" %}',
                method: 'post',
                data: form.serialize(),
                success: function(data) {
                    $('#message').html(data);
                }
            });

            return false;
        });
    });
</script>