How do I call an API when a website page loads?

Viewed 108

I need some help. So, I want to call this API and display the file given by it on my website

this is the link:

https://ogramcloud.com/api/download/061b78fb83ee928748b78bc7ee9f3e98

It generates this:

{
  "download_link": "http://ogramcloud.com/static/files/Fly_Me_to_the_Moon_Evangelion_OST.mp3", 
  "file_key": "061b78fb83ee928748b78bc7ee9f3e98", 
  "message": "file restored successfully !", 
  "status": "success"
}

I need to call this and display the http://ogramcloud.com/static/files/Fly_Me_to_the_Moon_Evangelion_OST.mp3 as a <audio> on my website.

how would I go to do that?

3 Answers

You can use jQuery to do that:

$(function () {
  $.get("https://ogramcloud.com/api/download/061b78fb83ee928748b78bc7ee9f3e98", function (response) {
    link = JSON.parse(response).download_link
    // append a <source> to your <audio> or do whatever you want with the link
  })
})

Here is the working solution using js fetch api.

var audioLink ;
var audio = document.getElementById("audio");
var audioSource = document.getElementById("audioSource");

fetch("https://ogramcloud.com/api/download/061b78fb83ee928748b78bc7ee9f3e98").then(response => response.json()).then(data => 
{
audioSource.src = data.download_link;
audio.load();
audio.play();
});
<audio id="audio" controls="controls">
  <source id="audioSource" src=""></source>
  Your browser does not support the audio format.
</audio>

Using the fetch api or XMLHttpRequest, you can make a request to your api.

Add an id to the audio in the HTML.

let audio = document.getElementById("audio");

fetch("https://ogramcloud.com/api/download/061b78fb83ee928748b78bc7ee9f3e98")
  .then(response => response.json())
  .then(data => {
    audio.src = data.download_link;
    audio.load();
    audio.play();
});
<audio controls="controls" src="" id="audio">
  Your browser does not support the HTML5 Audio element.
</audio>

Related