I'm creating a website using Django, and using Ajax to prevent site reload after submitting a form. Right now, I have orders being displayed on the site with an x button beside each order. Clicking the x cancels the order on the database (a post request that changes a value rather than simply deleting it) and also reloads the div in which the orders are housed. I have other forms on this website that are working correctly (they do have fields, though and use crispyforms). The problem I'm facing is that the script isn't detecting that the form is submitted.
Here are the pertinent parts of my project:
views.py
class CancelForm(ModelForm):
class Meta:
model = Order
fields = ['Filled']
...
def cancelorder(request, pk):
form = CancelForm(request.POST)
if request.is_ajax and request.method == "POST":
order = Order.objects.get(pk=pk)
order.Filled = "C"
instance = order.save(update_fields=["Filled"])
return JsonResponse({"canceled": pk}, status=200)
return JsonResponse({"error": ""}, status=400)
urls.py
urlpatterns = [
path('', views.orderpage, name="order-index"),
path('cancel_order/<int:pk>/', views.cancelorder, name="cancel_order"),
path('post/ajax/order/', views.postorder, name = "post_order"),
path('yourorders/', views.yourorders, name="your_orders"),
path('allorders/', views.allorders, name="all_orders"),
]
orderpage.html (this is my main page, with the div that is to be reloaded on yourorders.html)
<div class="container-fluid ActiveOrderInfoDiv" id="YourOrdersDiv">
{% include 'order/yourorders.html' %}
</div>
yourorders.html
{% for order in all_orders %}
<div class="row">
...
<div class="col">{{ order.OrderID }}</div>
<form action="{% url 'order:cancel_order' pk=order.OrderID %}" id="cancel_button" method="POST">
{% csrf_token %}
<button type="submit" class="close" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</form>
</div>
{% endfor %}
Javascript (here, check 2 is never logged)
$(document).ready(function () {
$("#cancel_button").submit(function (e) {
console.log("check 2");
e.preventDefault();
console.log("check 3");
$.ajax({
url: "{% url 'order:your_orders' %}",
success: function (response) {
$("#YourOrdersDiv").load("/order/yourorders/");
},
error: function (response) {
}
});
});
});
What I've tried
- Moved the script to yourorders.html (I thought maybe the JS wasn't seeing the cancel_button ID)
- Used console.log to see where the flow stopped (it doesn't seem to pick up that the cancel button was submitted)
- Added the CancelForm modelform (previously I was updating the DB without a modelform)
- Generally poking around with Ajax syntax and order
- Looking at other questions here on StackOverflow - I seem to be following them, and my syntax may just be right, it's just not picking up that the cancel_button form is being submitted