santosh Chauhan
santosh Chauhan

Reputation: 77

Getting Error while deleting Cart item using DestroyAPIView with Javascript. (Django)

I'm using DestroyAPIView with Javascript to delete the cart item in Django

While clicking on delete button it shows the following error on chrome console:

jquery.min.js:2 DELETE http://127.0.0.1:8000/showdata/2342; 404 (Not Found)
send @ jquery.min.js:2
ajax @ jquery.min.js:2
destoryCart @ (index):46
onclick @ (index):1

(index):55 {readyState: 4, getResponseHeader: ƒ, getAllResponseHeaders: ƒ, setRequestHeader: ƒ, overrideMimeType: ƒ, …} 

and in vs code terminal showing:

Not Found: /showdata/2342;

and all my code goes here:

views.py

class CartDestroyAPIView(DestroyAPIView): # DeleteView
    permission_classes = [IsAuthenticated] # Or anything else you want
    authentication_classes = [SessionAuthentication]  # Or anything else you want
    serializer_class = productserializers
    queryset = Cart.objects.all() 

index.html

<script>
      $(document).ready(function() {
        $.ajax({
          url: 'http://127.0.0.1:8000/showdata ',
          dataType: 'JSON',
          success: function(data){
            for (var i = 0; i < data.length; i++)
            {
              var row = 
              $('<tr><td style="font-style:bold">'
                +data[i].product.name+'</td><td style="font-style:bold">'
                  +data[i].product.price+'</td><td><a href='
                    +data[i].product.link_href+'><button type="button" class="btn btn-outline-success">Buy</button></a></td><td><button onclick="destoryCart('+data[i].product.id+')" type="button" class="btn btn-outline-danger">DELETE</button></td></tr>');
              $("#tableProduct").append(row);
            }
          }
        });
    });
    
    const destoryCart = (id) => {
      let url = `http://127.0.0.1:8000/showdata/${id};`
      $.ajax({
          beforeSend: function(xhr){xhr.setRequestHeader('X-CSRFToken', "{{ csrf_token }}");
        },
          url: url,
          type: 'DELETE',
          success: (data) => {
              console.log("deleted!");
          },
          error: (err) => {
              console.log(err);
          }
      });
    };
    </script>  

urls.py

path('cart_destroy/<int:pk>', views.CartDestroyAPIView.as_view(), name ='cart_destroy'),

WHAT IS WRONG GOING WITH THIS CODE.

Upvotes: 1

Views: 205

Answers (1)

Ankit Tiwari
Ankit Tiwari

Reputation: 4710

Change your URL in ajax call you have to put this URL in side your destoryCart()

 let url = `http://127.0.0.1:8000/cart_destroy/${id};`

instead of this URL http://127.0.0.1:8000/showdata/${id};

UPDATE

get csrf_token like this i don't know if there is another way but as per official doc.

function getCookie(name) {
    let cookieValue = null;
    if (document.cookie && document.cookie !== '') {
        const cookies = document.cookie.split(';');
        for (let i = 0; i < cookies.length; i++) {
            const cookie = cookies[i].trim();
            // Does this cookie string begin with the name we want?
            if (cookie.substring(0, name.length + 1) === (name + '=')) {
                cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
                break;
            }
        }
    }
    return cookieValue;
}
const csrftoken = getCookie('csrftoken');

And you ajax call

    const destoryCart = (id) => {
        $.ajax({
            type: 'POST',
            url: "{% url 'cart_destroy' %}",
            data: {
                'product_id': id,
                'csrfmiddlewaretoken': csrftoken,
        },
        
        success: function(success) {
        console.log('success : '+success.responseText)
        },
        
        error: function(error) {
        console.log('error : '+error.responseText)
        },
        
        });
    
    }

and you have to update your URL also like this

path('cart_destroy/', views.CartDestroyView, name ='cart_destroy'),

add this in your views.py

def CartDestroyView(request):
    if request.method == "POST":
      product_id = request.POST['product_id']
      Cart.objects.filter(id=product_id).delete()
      return HttpResponse({'Success':"Deleted Successfully."})

Upvotes: 1

Related Questions