Skip to content
Advertisement

Retun data from a Django view after a javascript AJAX POST request

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:

JavaScript

The javascript looks like this:

JavaScript

I was hoping that xhttp.responseText would print Thankyou to the console.

The Django View function looks like this:

JavaScript

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

JavaScript

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

JavaScript
Advertisement