How to store the onclick events in a Django database?

Viewed 112

I have a list of audio files displayed in my Django webpage displayed using ... tag. When a registered user clicks the play button of the audio file, it should start playing the audio and behind the scene, I want to store the audio file id as well as the user details in the database, like submission of a Django form. But after the user clicks the play button, I don't want the page to get refreshed, neither do I want the audio file to be paused. I guess this has to do something with the Ajax, but I can't figure it out.

1 Answers

Sounds like you are trying to make a request to an audio file stored on your server, without having to refresh the page.

To do this, you can make an HTTP request using ajax, you just need the direct link to your audio file. In order to make an HTTP request on the client side in JavaScript, you can use XMLHttpRequest or fetch. An example with fetch, assuming the url to the audio file is stored in a string variable named audioURL:

fetch(audioURL)
.then(response => response.blob())
.then(blob => {
    ///assuming you have an `audio` element on the page with id `audioEl`:
    audioEl.src = URL.createObjectURL(blob);
    audioEl.play();
});
Related