I am using Javascript to send an asynchronous request to a Django View. The View is able to receive data from the POST request, but I can’t seem to return a message to confirm that everything worked. I was expecting that xhttp.responseText
would contain the message Thankyou
, but it is empty.
The html part looks like this:
<textarea id="message"></textarea> <input type="submit" value="Send" id="send_button onclick="submit_message()"/>
The javascript looks like this:
function submit_message(){ document.getElementById("send_button").value="Sent - Thankyou!"; message = document.getElementById("message").value var xhttp = new XMLHttpRequest(); xhttp.open("POST", "/send-message"); xhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded"); xhttp.send("csrfmiddlewaretoken={{ csrf_token }}&message="+message); console.log('Sent POST request') console.log(xhttp.responseText) }
I was hoping that xhttp.responseText
would print Thankyou
to the console.
The Django View function looks like this:
def send_message(request): message = request.POST.get('message') print(message) return HttpResponse('Thankyou')
The message
variable prints out as expected, but Thankyou
doesn’t seem to be returned.
I am doing AJAX with JS for the first time, so I expect I’ve just misunderstood something simple.
— EDIT — I have it working, after following the suggestion and reading this https://developer.mozilla.org/en-US/docs/Web/Guide/AJAX/Getting_Started
After the line xhttp.send(… I have this function
xhttp.onreadystatechange = function handle_response(){ if (xhttp.readyState === XMLHttpRequest.DONE) { // Everything is good, the response was received. console.log('Things are good') console.log(xhttp) console.log(xhttp.response) } else { // Not ready yet. console.log('Not ready') } }
It wasn’t necessary to use JsonResponse, but I will give that a try as well.
Advertisement
Answer
I can only recommend to you, the usage of JsonResponse instead of HttpResponse for confirm your submit. Your problem I presume it is in JS, you need to confirm the server response, check this article for better understand of ajax requests https://developer.mozilla.org/es/docs/Web/Guide/AJAX/Getting_Started#segundo_paso_.e2.80.93_procesando_la_respuesta_del_servidor
if (xhttp.readyState == 4) { // response received console.log(xhttp.responseText) } else { // server not ready yet console.log("Server not ready") }