Successfully sending and receiving a JSON object in my views.py
file using a POST
request (AJAX), but facing difficulty with
return render(request, "pizza/confirmation.html")
. I want the server to perform backend logic on the database and then render a different template for confirmation. However, I am unsure of how to achieve this without utilizing AJAX to transfer a large JSON object. Below is my view:
@login_required
def basket(request):
if request.method == "POST":
selection = json.dumps(request.POST)
print(f"Selection is", selection) # selection appears fine
context = {"test": "TO DO"}
return render(request, "pizza/confirmation.html", context) # not functioning
I have attempted checks for request.is_ajax()
and tried using render_to_string
for my HTML page, yet it seems that my mistake lies elsewhere. Additionally, I notice in my console that a GET
request to my /basket
URL occurs after my POST
request - unclear why.
Below is my JavaScript code snippet:
var jsonStr = JSON.stringify(obj); //obj contains my data
const r = new XMLHttpRequest();
r.open('POST', '/basket');
const data = new FormData();
data.append('selection', jsonStr);
r.onload = () => {
// no specified callback needed and limited to using GET here anyway
};
r.setRequestHeader("X-CSRFToken", getCookie('csrftoken'));
r.send(data);
return false;