'Django retrieve checkbox values sent by Ajax POST request
I am trying to send form data to Django server via Javascript Ajax request specifically checkbox values, but at the server I read None values. here's the server code that reads:
@csrf_protect
def order_pizza(request):
if request.is_ajax() and request.method == "POST":
topps = Topping.objects.all()
for topp in topps:
mytop = request.POST.getlist('topping')
print(f"topp is {topp.__str__()} mytop is {mytop}")
return HttpResponse("pizza order!!")
And here's the html for the form:
<form id="form_pizza_order" class="form_pizza_order" method="post">
{% csrf_token %}
<div class="row">
<div class="order_topp_col col-12">
<header> Topping </header>
{% for topp in toppings %}
<input type="checkbox" id="{{ topp.name }}" name="topping" value="{{ topp.name }}">
<label for="{{ topp.name }}"> {{topp.name}}</label>
{% endfor %}
</div>
...
the print function returns a result :
topp is Pepperoni mytop is []
topp is Sausage mytop is []
topp is Mushrooms mytop is []
topp is Onions mytop is []
topp is Ham mytop is []
etc ...
what do I have to do to be able to read the checkboxes values ? thanks.
Solution 1:[1]
I had an error in javascript sending form data to server.
I used const FD = new FormData();
now I realized should have used:
let myform = document.getElementById("form_pizza_order");
const FD = new FormData(myform);
now the data is populated to the server.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | rajasaid |