I know javascript a little. But in a tutorial I have to add some jquery and ajax functionality.
here is a form:
<form class="form-product-ajax" method="POST" action="{% url 'carts:update' %}" class="form">
{% csrf_token %}
<input type="hidden" name="product_id" value=" {{p roduct.id}} "/>
{% if in_cart %}
<button type="submit" class="btn btn-link btn-sm" style="padding:0px;cursor:pointer;" name="button">Remove?</button>
{% else %}
<span class="submit-span">
{% if product in cart.products.all %}
In cart<button type="submit" class="btn btn-danger" name="button">Remove?</button>
{% else %}
<button type="submit" class="btn btn-success" name="button">Add to cart</button>
{% endif %}
</span>
{% endif %}
</form>
my jquery and ajax:
<script type="text/javascript">
$(document).ready(function(){
var productForm=$(".form-product-ajax")
productForm.submit(function(event){
event.preventDefault();
var thisForm=$(this)
var actionEndpoint=thisForm.attr("action");
var httpMethod=thisForm.attr("method");
var formData=thisForm.serialize();
$.ajax({
url:actionEndpoint,
method:httpMethod,
data:formData,
type : 'POST',
success: function(data){
var submitSpan = thisForm.find(".submit-span")
if(data.added){
submitSpan.html("<button type="submit" class="btn btn-danger" name="button">Remove?</button>")
}else{
submitSpan.html("<button type="submit" class="btn btn-success" name="button">Add to cart</button>")
}
},
error: function(errorData){
}
})
})
})
</script>
Here is my views.py’s function:
def cart_update(request):
#print(request.POST)
product_id=request.POST.get('product_id')
if product_id is not None:
try:
product_obj=Product.objects.get(id=product_id)
except Product.DoesNotExist:
print("Produuct does not exists")
return redirect("cart:home")
cart_obj,new_obj=Cart.objects.new_or_get(request)
if product_obj in cart_obj.products.all():
cart_obj.products.remove(product_obj)
added=False
else:
cart_obj.products.add(product_obj)
added=True
request.session['cart_items']=cart_obj.products.count()
if request.is_ajax():
print("Ajax request")
json_data={
"added": added,
"removed": not added,
}
return JsonResponse(json_data)
#return redirect(product_obj.get_absolute_url())
return redirect("carts:home")
jquery and ajax version:
{% load static %}
<script src="https://code.jquery.com/jquery-3.2.1.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.11.0/umd/popper.min.js" integrity="sha384-b/U6ypiBEHpOf/4+1nzFpr53nxSS+GLCkfwBdFNTxtclqqenISfwAzpKaMNFNmj4" crossorigin="anonymous"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-beta/js/bootstrap.min.js" integrity="sha384-h0AbiXch4ZDo7tp9hKZ4TsHbi047NrKGLO3SEJAg45jXxnGIfYzk4Si90RDIqNm1" crossorigin="anonymous"></script>
I can’t figure out why event.preventDefault(); not working whenever I add $.ajax in my project.If I comment it out event.preventDefault(); seems fine.After all ajax is not working on my project.
2
Answers
I find out the exact problem in this code.There the content of submitSpan.html below the if condition should be single quoted.
That's why console showed me this error:
According to django 3.1 release notes:
If you are writing your own AJAX detection method,
request.is_ajax()
can be reproduced exactly asrequest.headers.get('x-requested-with') == 'XMLHttpRequest'
.