Skip to content

How to fetch without refreshing the page?

Okay so, I recently started learning about async JS and APIs and fetch and am just creating a small project for practice and I want to add 2 more features to it

  1. I want to add a button on which when clicked without refreshing the page, gives us a new GIF.

  2. A search bar for the GIF we can find using that bar.

Here is my code:

<body>
  <img src="#" />
  <button>New Giffy</button>
  <script>
    const img = document.querySelector('img');
    const btn = document.querySelector('button');

    fetch(
        `https://api.giphy.com/v1/gifs/translate?api_key=pH9WHztAm5Yt9v5VAziRzXhOBvblWf6m&s=akatsuki`, {
          mode: 'cors'
        }
      )
      .then((response) => {
        return response.json();
      })
      .then((response) => {
        img.src = response.data.images.original.url;
      });
  </script>
</body>

Answer

you can provide onClick on button which will call the function defined in below code or refer fiddle

<body>
  <input type="text" placeholder="search here..." id="searchField" value="akatsuki">
  <button onClick="onGifClick()">New Giffy</button><br>
  <img src="#" />
  <script>
    function onGifClick() {
      const search = document.querySelector('#searchField');
      const img = document.querySelector('img');
      const btn = document.querySelector('button');
      debugger;
      fetch(
          `https://api.giphy.com/v1/gifs/translate?api_key=pH9WHztAm5Yt9v5VAziRzXhOBvblWf6m&s=` + search.value, {
            mode: 'cors'
          }
        )
        .then((response) => {
          return response.json();
        })
        .then((response) => {
          img.src = response.data.images.original.url;
        });
    }
    onGifClick();
  </script>
</body>