I originally had an AJAX call to my view, then I realized I can't return render(request, 'my/new/template.html, context)
So I came upon this related question, which led me to what I show below: Redirect to new page after receiving data from Javascript
However I'm having trouble getting the CSRF token to work, it's giving me a 403 error. As a side note, I am also using shell_plus to use a secure connection, but I don't think that is contributing to the issue.
Here is my call to the view function:
submitForm.addEventListener('submit', function (e) {
const form = new FormData(e.target);
// const csrf_token = form.get("csrfmiddlewaretoken");
// instead using var csrf_token = {{ csrf_token }} in template
e.preventDefault()
instance.requestPaymentMethod(function (err, payload) {
var url = '/shop/payment/';
var newForm = '<form action="' + url + '" method="post">';
newForm += '<input type="hidden" name="csrf_token" value="' + csrf_token +'" />'
newForm += '<input type="hidden" name="paymentMethodNonce" value="' + payload.nonce + '" />'
newForm += '<input type="hidden" name="orderTotal" value="' + order_total + '" />'
newForm += '<input type="hidden" name="address" value="' + $('#address-select').val() + '" />
newForm += '<input type="hidden" name="first-name" value="' + form.get("first-name") + '" />'
newForm += '<input type="hidden" name="last-name" value="' + form.get("last-name") + '" />'
newForm += '</form>'
var form_element = $(newForm);
$('body').append(form_element);
form_element.submit();
});
My previous attempt using ajax looked something like this:
$.ajax({
type: 'POST',
url: '/shop/payment/',
headers: { "X-CSRFToken": csrf_token },
data: {
'paymentMethodNonce': payload.nonce,
'orderTotal': order_total,
'address': $('#address-select').val(),
'first-name': form.get("first-name"),
'last-name': form.get("last-name")
}
}).done(function (result) {
console.log(result.result)
// WON'T REDIRECT
});