I'm trying to pass a Javascript array to my Django views. This works, but I would like to manipulate that data and display it in a separate url. So I have a products page, where you select items. When the form is submitted, this javascript is called, and I want it to redirect to a cart page:
$("#getArr").submit(function(){
var data = {'ab[]' : chosen};
$.post('cart/', data, function(response){
if(response == 'success'){
window.location.href="cart/" // references my views
}
else{
alert('Error! :(');
}
});
});
views.py
def cart(request):
if request.method == 'POST':
chosen = request.POST.getlist('ab[]')
print(chosen, file=sys.stderr)
template = loader.get_template('o/cart.html')
context = {'prodChosen': chosen,
'e': "hy"}
return HttpResponse('success')
# return HttpResponse(template.render(context, request))
else:
template = loader.get_template('o/cart.html')
context = {}
return HttpRepsonse('fail')
# return HttpResponse(template.render(context, request))
Like in the commented out HttpResponse lines, I need to pass data to my cart.html (it will be objects from one of my models). I have no idea how to pass data to my cart page.
The line print(chosen, file=sys.stderr)
has been quite useful.
Previously, when I had code that used the commented out return HttpResponse lines, it printed to my terminal both the desired array and an empty one. However, with this new code, the desired array prints out but it doesn't redirect to the new page. I'm not sure why this is happening, but I do know the fact the empty array printed out at as well in my earlier attempt meant my cart page wasn't receiving the correct array data.
Edit: I need to pass model objects to the new html page, which (from what I know) I can't do through javascript
index.html
<form id="getArr" method="POST">
{% csrf_token %}
<button type='submit' id="checkCart">Check Added Items</button>
</form>