Reputation: 23
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
Upvotes: 2
Views: 129
Reputation: 32244
You should delegate the event handler to the document level so that when the form is reloaded the event is still handled. When you "reload" the form you are inserting a new element into the DOM that does not have the event handler attached to it
$(document).on("submit", "#cancel_button", function(e) {
...
Upvotes: 1