Search code examples
javascriptjqueryhtmljsongiphy-api

GIPHY API - How do I search for Giphs?


My problem: Looks like my code is incorrect somewhere. Searching isn't working. I'm new to working with API's.

How can I get the specific search result that the user searches for?

GitHub link to the Giphy API is here: https://github.com/Giphy/GiphyAPI.

JS

document.addEventListener('DOMContentLoaded', function () {

//q = "";

request = new XMLHttpRequest;
//request.open('GET', 'http://api.giphy.com/v1/gifs/random?api_key=dc6zaTOxFJmzC&tag='+q, true);
request.open('GET', 'http://api.giphy.com/v1/gifs/search?q=funny+cat&api_key=dc6zaTOxFJmzC');


request.onload = function() {
    if (request.status >= 200 && request.status < 400){
        data = JSON.parse(request.responseText).data.image_url;
        console.log(data);
        document.getElementById("here_is_gif").innerHTML = '<center><img src = "'+data+'"  title="GIF via Giphy"></center>';
    } else {
        console.log('reached giphy, but API returned an error');
     }
};

request.onerror = function() {
    console.log('connection error');
};

request.send();
});

HTML

<h1> Let's Search Some Gifs! </h1>
<div class="info">
    <p> Search below to the wonderful world of Gifs! </p>
        <form class="gif-form">
            <input type="text" id="form-value" class="search-input-rounded">
            <button type="submit" class="search_button"> Search for GIFs </button>
            <input type="reset" value="Reset">
        </form>
        <div class="rando_facts animated bounceIn">
            <p id="here_is_gif"> </p>
        </div>
</div>

Solution

  • Once the user input is extracted, you can put in into a variable...

    Your API Link (copied here) is just searching for "funny cat". request.open('GET', 'http://api.giphy.com/v1/gifs/search?q=funny+cat&api_key=dc6zaTOxFJmzC');

    You can fix this by doing something like this...

    var searchTerm = prompt('Add your search term here'); searchTerm = searchTerm.trim().replace(/ /g, "+"); // adds a + wherever a space is request.open('GET', 'http://api.giphy.com/v1/gifs/search?q=' + searchTerm + '&api_key=dc6zaTOxFJmzC');

    Since, I'm not sure if you pasted all of the all the code you are using, I only demoed how you can substitute a phrase like funny+cat into a variable called searchTerm.

    In order to pull the user's input out of the <input> field, you use jQuery and then pass it into your search term variable.

    Oddly enough, I've done a project with the Giphy API.