• 45

A PHP Error was encountered

Severity: Notice

Message: Undefined index: userid

Filename: views/question.php

Line Number: 191


File: /var/www/html/cnasolution/site/application/views/question.php
Line: 191
Function: _error_handler

File: /var/www/html/cnasolution/site/application/controllers/Questions.php
Line: 419
Function: view

File: /var/www/html/cnasolution/site/index.php
Line: 315
Function: require_once

I have managed to send & receive my JSON object in my views.py with a POST request (AJAX), but am unable to return render(request, "pizza/confirmation.html"). I don't want to stay on the same page but rather have my server, do some backend logic on the database and then render a different template confirming that, but I don't see any other way other than AJAX to send across a (large) JSON object. Here is my view:

@login_required def basket(request):   if request.method == "POST":     selection = json.dumps(request.POST)     print(f"Selection is", selection) # selection comes out OK    context = {"test": "TO DO"}   return render(request, "pizza/confirmation.html", context) # not working   

I have tried checking for request.is_ajax() and also tried render_to_string of my html page, but it all looks like my mistake is elsewhere. Also I see in my terminal, that after my POST request, a GET request to my /basket url is called - don't understand why.

Here is my JavaScript 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 = () => {       // don't really want any callback and it seems I can only use GET here anyway      };     r.setRequestHeader("X-CSRFToken", getCookie('csrftoken'));     r.send(data);     return false; 
Download script demo [LINK] [Origin]
Download script demo [LINK 2] [Onedrive] Download script demo [LINK 2] [Google drive]

In your basket view function, you always render the template as response. You can pass the parameters to your js snippet via HttpResponse. After request completed and you have response in your js function, you can use window.location.href to redirect the page you want. You can also look this answer to get more information.

see demo
  • 11
Reply Report