Pass id from button in template to Django View

Viewed 304

im on my 2nd week trying to learn Python+Django and wanted to make a litte project. But im getting stuck on some JS-bs. I don't know JS well at all and would need some help.

I want to pass the ID ("Value" in the button) of the selected button as data in the Ajax function, but can't really get this to work.

How do i pass the value to the Ajax function? I want to use the value in the "id" variable in views.

Thank you!

HTML - I want to pass an ID of selected pressed button.

{% for product in products %}
   <button type="button" id="submit" class="btn" value="{{product}}">{{product}}</button>
{% endfor %}

Javascript To the Ajax POST function here.


<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script>
var data = new FormData();
 $(document).on('click', '#submit', function(e) {
  data.append('action', 'toggle_button')
  data.append('csrfmiddlewaretoken', '{{ csrf_token }}')
  $.ajax({
       type: 'POST',
       url: '{% url "toggle_button" %}',
       data: data,
       cache: false,
       processData: false,
       contentType: false,
       enctype: 'multipart/form-data',
  })
})
</script>

Django view file

from django.http import HttpResponse, request
from django.shortcuts import render
from django.http import JsonResponse

def home_view(request):
    context = {
    "products": ["Button1", "Button2", "Button3", "Button4"],
    }
    return render(request, "home.html", context)


def toggle_button_view(request):
    if request.POST.get('action') == 'toggle_button':
        token = request.POST.get('csrfmiddlewaretoken')
        id = request.POST.get("id")
        #print (token)
        print (id)
    return render(request, "home.html")
1 Answers

It is because you are not passing the ID to the view. I modified your JS event to handle the $(this) variable that contains the object that called the event:

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script>
var data = new FormData();
 $(document).on('click', '#submit', function(e) {
  data.append('action', 'toggle_button')
  data.append('csrfmiddlewaretoken', '{{ csrf_token }}')
  data.append('id', $(this).val())
  $.ajax({
       type: 'POST',
       url: '{% url "toggle_button" %}',
       data: data,
       cache: false,
       processData: false,
       contentType: false,
       enctype: 'multipart/form-data',
  })
})
</script>

Notice how I added data.append('id', $(this).val())

Related