Juanvulcano Juanvulcano - 1 year ago 75
HTML Question

Django - Display Jsonresponse after Fetch POST

I am currently posting audio through javascript fetch to a Django server, post-processing it and returning a JsonResponse.

I now would like to display the JsonResponse on my website as they come in.

I understand I need some type of listener in my JS that gets triggered with every POST request that is being made, probably after my fetch function or maybe a separate function?

My Js

function makeLink(){
let blob = new Blob(chunks, {type: media.type })
let fd = new FormData;
fd.append("audioRecording", blob);
fetch("https://localhost/news/audio/", {method:"POST", body:fd})
.then(response => response.ok)
.then(res => console.log(res))
.catch(err => console.error(err));

This POSTS the audio and triggers the following views.py:

def audio(request):
if request.method == 'POST':
#Store audio
#Make some API calls
return JsonResponse({"abc":123})

Now let's suppose I have a TextField in plain html and I would like the JsonResponse to be displayed in the TextField without the need of reloading the website.

<!DOCTYPE html>
<textarea id="text">
Response should be here

How can I achieve this?

Answer Source

here my post, which i also commented to your question:

If you want to add your response to your custom textbox, you need to do this with javascript. Actualy you only print your response into the web-console:


This part could you change to add your response to your textbox. With jquery it could look so:

$('#text').append(res);   // If 'res' is your response you want to add

If you want to add something other then only replace 'res'.

Also I would recommend you to work with the django-restframework. I also work with this framework. Try a look -> django-rest-framework

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download