0

I'm ridiculously new to Javascript. I am able to fetch a page and access the resulting JSON when using console.log but I do not now how to then access the JSON to save variables. I have tried with no luck to find the right direction myself online.

{"video":"ads/003.mp4","rpv":0.004776,"id":"0001"}

function fetchAd() {
    fetch('https://www.****/getAd.php')
    .then((res) => res.json())
  .then((data) => console.log(data.video))
  .catch((error) => console.log(error))
}

What do I need to learn to access JSON to save variable?

  • can you elaborate on what you mean by "save a variable"? Do you want to download the .mp4 file? Or do you want to persist something so that it's there the next time you visit the page? Or do you just want to save that string in memory so that it is there the next time an ad is fetched? This could use more explanation. Otherwise, to literally store a string in a variable just use `somevar = data.video`. declare `somevar` with appropriate scope somewhere with `var somevar` – Wyck May 21 '21 at 14:22
  • The PHP file queries DB and saves most appropriate ad into a JSON. I just want to save the video value so that I can use it later in the script to display the video. So yeah I just want to store it as a variable, but when I do as you've said I get uncaught in promise. – Danny Watts May 21 '21 at 14:34
  • Show the code that produces the error. – Wyck May 21 '21 at 14:35
  • `function fetchAd() { var somevar; fetch('https://www.****/getAd.php') .then((res) => res.json()) .then((data) => somevar = data.video) .catch((error) => console.log(error)) video.src = somevar; video.play(); }` – Danny Watts May 21 '21 at 14:37
  • Hi, Danny, you should modify your question to include that code that you just commented. The problem is that you are using an asynchronous call (the fetch) and the code `somevar = data.video` hasn't executed yet by the time you do `video.src = somevar`. The `fetch` just starts the ball rolling. the completion code doesn't execute until the fetch response comes back from the internet, so you're playing a video where the `src` is undefined. – Wyck May 21 '21 at 14:41

0 Answers0