0

I'm so close! and a bit confused...so tell me if I'm over-complicating things.

I'm using the public Giphy API to pull up a random gif (tag=dog in example below) and want to cycle through new ones each time a button is clicked.

In the example below, I get the console to log "success," I just can't quite figure out how to set the new random URL as the source.

Any help is appreciated, thanks in advance!

HTML:

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

<button type='button' class="btn btn-default" id="new"> New GIF
</button>

JS/jQuery:

$("#new").click(function () {
  var gif = $('#giphy-embed').attr('src', function(newGIF){ //This is where it will go!
  $.ajax ({
    url: "//api.giphy.com/v1/gifs/random?api_key=dc6zaTOxFJmzC&tag=dog",
    type: "GET",
    success: function(response) {

      console.log("success");    //This is what I get, just need to set the new URL as the src
    }, 
    error: function(e) {
      console.log("uh oh");
      }
    });
  });

});
Ben Thompson
  • 37
  • 1
  • 6

1 Answers1

0

Try updating the iframe src as part of the success function instead.

$("#new").click(function () {
 //This is where it will go!
  var imgSrc;
  $.ajax ({
    url: "//api.giphy.com/v1/gifs/random?api_key=dc6zaTOxFJmzC&tag=dog",
    type: "GET",
    success: function(response) {
      // console.log(response);
      imgSrc = response.data.image_url;
      $("#giphy-embed").attr("src", imgSrc);
      return false;
    }, 
    error: function(e) {
      console.log("uh oh");
      }
    });
});
partypete25
  • 4,353
  • 1
  • 17
  • 16
  • I see where you are coming from and I like it! It's just not quite working. The console brings up the whole ajax response and all. Here's a link to the CodePen https://codepen.io/benthom21/pen/qjRzJV?editors=1011 – Ben Thompson Jun 19 '17 at 11:34
  • It works fine - try it out on your localhost or server. There is a mixed content error on codepen because it is loaded over https and giphy is http. – partypete25 Jun 19 '17 at 23:27
  • I mean the response.data.image_url is http. I made a tweak to just update the image src id. this will work. imgSrc = response.data.id; $("#giphy-embed").attr("src", "https://giphy.com/embed/"+imgSrc); – partypete25 Jun 19 '17 at 23:36