0

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;
Anna
  • 359
  • 1
  • 4
  • 13

1 Answers1

1

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.

Deniz Kaplan
  • 1,549
  • 1
  • 13
  • 18
  • I'm looking into the response, but as far as I understand from here (https://stackoverflow.com/questions/2367979/pass-post-data-with-window-location-href), with ```window.location.href``` it's not possible to send a ```POST``` request – Anna May 15 '20 at 07:08
  • You are right. I didn't understand your aim from the question about sending post request after ajax request finished. Can you update your question with detailed information about the steps you want after ajax request? Btw, I think Django Forms will be better for redirect operations. – Deniz Kaplan May 15 '20 at 07:34