skip to Main Content

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


  1. Chosen as BEST ANSWER

    I find out the exact problem in this code.There the content of submitSpan.html below the if condition should be single quoted.

    submitSpan.html('<button type="submit" class="btn btn-danger" name="button">Remove?</button>')
    

    That's why console showed me this error:

    (index):138 Uncaught SyntaxError: missing ) after argument list
    

  2. According to django 3.1 release notes:

    The HttpRequest.is_ajax() method is deprecated as it relied on a jQuery-specific way of signifying AJAX calls, while current usage tends to use the JavaScript Fetch API. Depending on your use case, you can either write your own AJAX detection method, or use the new HttpRequest.accepts() method if your code depends on the client Accept HTTP header.

    If you are writing your own AJAX detection method, request.is_ajax() can be reproduced exactly as request.headers.get('x-requested-with') == 'XMLHttpRequest'.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search