I have add_to_cart button in my html. When it is clicked, I want to take selected content and send it to my views.py. I have created an ajax request and I wish to send item object through URL to my views.py. Keep in mind that inside item, toppings and extra are NodeList. And I am using Django.
add_to_cart.addEventListener("click", ()=>{
const item = {
"item_name": document.querySelector("#itemname").textContent,
"quantity" : document.querySelector("#quantity").value,
"price" : document.querySelector("#price").dataset.price,
"size" : document.querySelector(".size:checked").value,
"toppings" : document.querySelectorAll(".topping:checked"),
"extra" : document.querySelectorAll(".extra:checked")
}
const request = new XMLHttpRequest();
request.open('GET', `/cart_item/${item}`, true);
request.onload = () => {
const data = JSON.parse(request.responseText);
if (data.success){
window.location.href = `http://127.0.0.1:8000/cart/cart_item/${item}`;
}
else{
window.location.href = "http://127.0.0.1:8000/user/login";
}
}
request.send();
return false;
})
in my urls.py
urlpatterns = [
path("", views.index, name="cart"),
path("cart_item/<item>", views.cart_item, name="cart_item")
]
And in views.py
def cart_item(request, item):
if not request.user.is_authenticated:
print("okay")
messages.error(request, "Please login first to add to cart.")
return JsonResponse({"success": False})
return JsonResponse({"success": True})
Above is what I tried to do, but I get this error Not Found: /cart_item/[object Object] I have also tried to search on Google the correct way to do this but could not find a satisfactory explanation. If you have a solution or an explanation on how to pass object in URL, please tell. Thanks a lot in advance.