jQuery: Updating iframe src with Random GIF URLs from Giphy API

I’m working with the Giphy API and having trouble with the final step. I want to display random dog gifs in an iframe and change to a new random gif when someone clicks a button.

The API call works fine and I can see the success message in console, but I can’t figure out how to actually update the iframe source with the new gif URL from the response.

Here’s my current setup:

HTML Structure:

<div class="gif-container">
  <iframe src="https://giphy.com/embed/26FmRLBRZfpMNwWdy" id="gif-frame">
  </iframe>
</div>

<button type='button' class="btn btn-primary" id="refresh-gif"> Get New GIF
</button>

JavaScript Code:

$("#refresh-gif").click(function () {
  var gifFrame = $('#gif-frame').attr('src', function(updateGIF){ 
  $.ajax ({
    url: "//api.giphy.com/v1/gifs/random?api_key=dc6zaTOxFJmzC&tag=dog",
    type: "GET",
    success: function(data) {
      console.log("success");    // This works, but how do I update the src?
    }, 
    error: function(err) {
      console.log("failed");
      }
    });
  });
});

I think I’m overcomplicating this but I’m stuck on extracting the gif URL from the response and setting it as the new iframe source. Any suggestions would be really helpful!

You’re setting the iframe src before the AJAX call finishes. Move that code into the success callback where you can actually access the response data.

Here’s how to fix it:

$("#refresh-gif").click(function () {
  $.ajax ({
    url: "//api.giphy.com/v1/gifs/random?api_key=dc6zaTOxFJmzC&tag=dog",
    type: "GET",
    success: function(data) {
      var embedUrl = data.data.embed_url;
      $('#gif-frame').attr('src', embedUrl);
    }, 
    error: function(err) {
      console.log("failed");
    }
  });
});

Grab data.data.embed_url from the Giphy response - that’s the URL that works with iframes. I’ve used this setup in several projects and it updates smoothly without flickering.