1

First off, I'm very new to working with APIs at all. And English is not my first language. I've searched the web but came up short in finding exactly what I'm looking for, or at least I have not understood enough of what I read to understand how to alter and apply it to my situation.

I'm working with the Omdb API and the Giphy API, making a silly page. I'm using JavaScript and HTML.

At the end I want the page to display the search result of the user searching for a movie + on-topic gifs.

I've come so far that I have a result from both APIs. That's all good and well. What I don't know how to do is to from these results present, for example, just the movie titles and the .gif-files. My attempts at splitting the returned results have so far failed. Any suggestions? Below is my JavaScript code.

var form = document.getElementById('search-form');

form.addEventListener("submit", search);

function search(event) {
  event.preventDefault();
  document.getElementById("present_result").innerHTML = "";
  if(this.elements.query.value === '') {
    alert("Enter search word!");
  } else {
    var rawInputData = this.elements.query.value;
    var fixedInputData = rawInputData.split(" ");
    var inputData = encodeQueryData(fixedInputData);
    var inputDataGif = encodeQueryDataGif(fixedInputData);

    function encodeQueryData(data) {
       let ret = [];
       for (let d in data)
         ret.push(encodeURIComponent(data[d]));
       return ret.join('%20');
    }

    function encodeQueryDataGif(data) {
       let ret = [];
       for (let d in data)
         ret.push(encodeURIComponent(data[d]));
       return ret.join('+');
    }

    var omdbAPI = new XMLHttpRequest();
    var gifAPI = new XMLHttpRequest();
    var omdbURL = "http://www.omdbapi.com/?s=" + inputData + "&type=movie";
    var gifURL = "http://api.giphy.com/v1/gifs/search?q=" + inputDataGif + "&limit=1&api_key=dc6zaTOxFJmzC";

    omdbAPI.addEventListener("load", function() {
      if (this.responseText === '{"Response":"False","Error":"Movie not found!"}')
      {
        alert("No result.");
      } else {
        var result = JSON.parse(this.responseText);
        console.log(result);
        result = JSON.stringify(result);
        document.getElementById("present_result").innerHTML = result;
      }
    });

      gifAPI.addEventListener("load", function() {
        if (this.responseText === '{"Response":"False","Error":"Not found!"}')
        {
          alert("No Result.");
        } else {
          var result = JSON.parse(this.responseText);

          console.log(result);
          result = JSON.stringify(result);
          document.getElementById("present_gif").innerHTML = result;
        }
      });

    omdbAPI.open("get", omdbURL, true);
    omdbAPI.send();
    gifAPI.open("get", gifURL, true);
    gifAPI.send();
  }
}

And below the HTML.

<!doctype html>
<html>
    <head>
        <meta charset="utf-8">
        <title>Mashup test</title>
        <link rel="stylesheet" type="text/css" href="style.css">
    </head>
    <body>
      <!-- Form -->
      <form action="" method="get" id="search-form" class="search-form">
          Movie: <input type="text" name="query">
          <button type="submit" id="submit">Search</button>
      </form>

      <!-- Result -->
      <div id="present_result">
      </div>
      <div id="present_gif">
      </div>
      <script src="scripts.js"></script>
    </body>
</html>

And here's a sample result from OMDb:

{
    "Search": [{
        "Title": "Titanic",
        "Year": "1997",
        "imdbID": "tt0120338",
        "Type": "movie",
        "Poster": "https://images-na.ssl-images-amazon.com/images/M/MV5BZDNiMjE0NDgtZWRhNC00YTlhLTk2ZjItZTQzNTU2NjAzNWNkXkEyXkFqcGdeQXVyNjUwNzk3NDc@._V1_SX300.jpg"
    }, {
        "Title": "Titanic II",
        "Year": "2010",
        "imdbID": "tt1640571",
        "Type": "movie",
        "Poster": "https://images-na.ssl-images-amazon.com/images/M/MV5BMTMxMjQ1MjA5Ml5BMl5BanBnXkFtZTcwNjIzNjg1Mw@@._V1_SX300.jpg"
    }, {
        "Title": "Titanic: The Legend Goes On...",
        "Year": "2000",
        "imdbID": "tt0330994",
        "Type": "movie",
        "Poster": "https://images-na.ssl-images-amazon.com/images/M/MV5BMTg5MjcxODAwMV5BMl5BanBnXkFtZTcwMTk4OTMwMg@@._V1_SX300.jpg"
    }, {
        "Title": "Titanic",
        "Year": "1953",
        "imdbID": "tt0046435",
        "Type": "movie",
        "Poster": "https://images-na.ssl-images-amazon.com/images/M/MV5BMTU3NTUyMTc3Nl5BMl5BanBnXkFtZTgwOTA2MDE3MTE@._V1_SX300.jpg"
    }, {
        "Title": "Raise the Titanic",
        "Year": "1980",
        "imdbID": "tt0081400",
        "Type": "movie",
        "Poster": "https://images-na.ssl-images-amazon.com/images/M/MV5BMTY5MTQwNzMxNV5BMl5BanBnXkFtZTcwMzkwOTMyMQ@@._V1_SX300.jpg"
    }, {
        "Title": "The Legend of the Titanic",
        "Year": "1999",
        "imdbID": "tt1623780",
        "Type": "movie",
        "Poster": "https://images-na.ssl-images-amazon.com/images/M/MV5BMjMxNDU5MTk1MV5BMl5BanBnXkFtZTgwMDk5NDUyMTE@._V1_SX300.jpg"
    }, {
        "Title": "The Chambermaid on the Titanic",
        "Year": "1997",
        "imdbID": "tt0129923",
        "Type": "movie",
        "Poster": "https://images-na.ssl-images-amazon.com/images/M/MV5BMWUzYjgyNDEtNTAyMi00M2JjLTlhMzMtMDJmOGM1ZmYzNzY4XkEyXkFqcGdeQXVyMTA0MjU0Ng@@._V1_SX300.jpg"
    }, {
        "Title": "In Search of the Titanic",
        "Year": "2004",
        "imdbID": "tt1719665",
        "Type": "movie",
        "Poster": "https://images-na.ssl-images-amazon.com/images/M/MV5BMTAzNjY0NDA2NzdeQTJeQWpwZ15BbWU4MDIwMzc1MzEx._V1_SX300.jpg"
    }, {
        "Title": "Titanic",
        "Year": "1943",
        "imdbID": "tt0036443",
        "Type": "movie",
        "Poster": "https://images-na.ssl-images-amazon.com/images/M/MV5BMTU2Njg4MDgxN15BMl5BanBnXkFtZTcwNzE4MjYyMQ@@._V1_SX300.jpg"
    }, {
        "Title": "S.O.S. Titanic",
        "Year": "1979",
        "imdbID": "tt0079836",
        "Type": "movie",
        "Poster": "https://images-na.ssl-images-amazon.com/images/M/MV5BMTMwOTU5MDU0OV5BMl5BanBnXkFtZTcwMDc4OTYyMQ@@._V1_SX300.jpg"
    }],
    "totalResults": "170",
    "Response": "True"
}

And sample result from Giphy:

{
    "data": [{
        "type": "gif",
        "id": "pWDH6fkHgGHza",
        "slug": "titanic-leonardo-dicaprio-pWDH6fkHgGHza",
        "url": "http://giphy.com/gifs/titanic-leonardo-dicaprio-pWDH6fkHgGHza",
        "bitly_gif_url": "http://gph.is/Z15kA0",
        "bitly_url": "http://gph.is/Z15kA0",
        "embed_url": "http://giphy.com/embed/pWDH6fkHgGHza",
        "username": "",
        "source": "http://tomhiddles.tumblr.com/post/37231367662",
        "rating": "g",
        "content_url": "",
        "source_tld": "tomhiddles.tumblr.com",
        "source_post_url": "http://tomhiddles.tumblr.com/post/37231367662",
        "is_indexable": 0,
        "import_datetime": "2013-03-24 01:54:54",
        "trending_datetime": "1970-01-01 00:00:00",
        "images": {
            "fixed_height": {
                "url": "http://media0.giphy.com/media/pWDH6fkHgGHza/200.gif",
                "width": "513",
                "height": "200",
                "size": "271598",
                "mp4": "http://media0.giphy.com/media/pWDH6fkHgGHza/200.mp4",
                "mp4_size": "19808",
                "webp": "http://media0.giphy.com/media/pWDH6fkHgGHza/200.webp",
                "webp_size": "392604"
            },
            "fixed_height_still": {
                "url": "http://media0.giphy.com/media/pWDH6fkHgGHza/200_s.gif",
                "width": "513",
                "height": "200"
            },
            "fixed_height_downsampled": {
                "url": "http://media0.giphy.com/media/pWDH6fkHgGHza/200_d.gif",
                "width": "513",
                "height": "200",
                "size": "530508",
                "webp": "http://media0.giphy.com/media/pWDH6fkHgGHza/200_d.webp",
                "webp_size": "196204"
            },
            "fixed_width": {
                "url": "http://media0.giphy.com/media/pWDH6fkHgGHza/200w.gif",
                "width": "200",
                "height": "78",
                "size": "65057",
                "mp4": "http://media0.giphy.com/media/pWDH6fkHgGHza/200w.mp4",
                "mp4_size": "24950",
                "webp": "http://media0.giphy.com/media/pWDH6fkHgGHza/200w.webp",
                "webp_size": "74208"
            },
            "fixed_width_still": {
                "url": "http://media0.giphy.com/media/pWDH6fkHgGHza/200w_s.gif",
                "width": "200",
                "height": "78"
            },
            "fixed_width_downsampled": {
                "url": "http://media0.giphy.com/media/pWDH6fkHgGHza/200w_d.gif",
                "width": "200",
                "height": "78",
                "size": "100970",
                "webp": "http://media0.giphy.com/media/pWDH6fkHgGHza/200w_d.webp",
                "webp_size": "37622"
            },
            "fixed_height_small": {
                "url": "http://media0.giphy.com/media/pWDH6fkHgGHza/100.gif",
                "width": "256",
                "height": "100",
                "size": "271598",
                "mp4": "http://media0.giphy.com/media/pWDH6fkHgGHza/100.mp4",
                "mp4_size": "170265",
                "webp": "http://media0.giphy.com/media/pWDH6fkHgGHza/100.webp",
                "webp_size": "98852"
            },
            "fixed_height_small_still": {
                "url": "http://media0.giphy.com/media/pWDH6fkHgGHza/100_s.gif",
                "width": "256",
                "height": "100"
            },
            "fixed_width_small": {
                "url": "http://media0.giphy.com/media/pWDH6fkHgGHza/100w.gif",
                "width": "100",
                "height": "39",
                "size": "65057",
                "mp4": "http://media0.giphy.com/media/pWDH6fkHgGHza/100w.mp4",
                "mp4_size": "45670",
                "webp": "http://media0.giphy.com/media/pWDH6fkHgGHza/100w.webp",
                "webp_size": "23380"
            },
            "fixed_width_small_still": {
                "url": "http://media0.giphy.com/media/pWDH6fkHgGHza/100w_s.gif",
                "width": "100",
                "height": "39"
            },
            "downsized": {
                "url": "http://media0.giphy.com/media/pWDH6fkHgGHza/giphy.gif",
                "width": "500",
                "height": "195",
                "size": "1006467"
            },
            "downsized_still": {
                "url": "http://media0.giphy.com/media/pWDH6fkHgGHza/giphy_s.gif",
                "width": "500",
                "height": "195"
            },
            "downsized_large": {
                "url": "http://media0.giphy.com/media/pWDH6fkHgGHza/giphy.gif",
                "width": "500",
                "height": "195",
                "size": "1006467"
            },
            "downsized_medium": {
                "url": "http://media0.giphy.com/media/pWDH6fkHgGHza/giphy.gif",
                "width": "500",
                "height": "195",
                "size": "1006467"
            },
            "original": {
                "url": "http://media0.giphy.com/media/pWDH6fkHgGHza/giphy.gif",
                "width": "500",
                "height": "195",
                "size": "1006467",
                "frames": "12",
                "mp4": "http://media0.giphy.com/media/pWDH6fkHgGHza/giphy.mp4",
                "mp4_size": "84279",
                "webp": "http://media0.giphy.com/media/pWDH6fkHgGHza/giphy.webp",
                "webp_size": "378130"
            },
            "original_still": {
                "url": "http://media0.giphy.com/media/pWDH6fkHgGHza/giphy_s.gif",
                "width": "500",
                "height": "195"
            },
            "looping": {
                "mp4": "http://media.giphy.com/media/pWDH6fkHgGHza/giphy-loop.mp4"
            },
            "preview": {
                "mp4": "http://media3.giphy.com/media/pWDH6fkHgGHza/giphy-preview.mp4",
                "mp4_size": "44332",
                "width": "326",
                "height": "126"
            },
            "downsized_small": {
                "mp4": "http://media3.giphy.com/media/pWDH6fkHgGHza/giphy-downsized-small.mp4",
                "mp4_size": "116662"
            }
        }
    }],
    "meta": {
        "status": 200,
        "msg": "OK",
        "response_id": "5887622069432538bfa2a521"
    },
    "pagination": {
        "total_count": 11258,
        "count": 1,
        "offset": 0
    }
}
spender
  • 117,338
  • 33
  • 229
  • 351
Zarkaylia
  • 61
  • 4
  • 13
  • 1
    What do you have in `result` after you do `var result = JSON.parse(this.responseText);`? – Majid Fouladpour Jan 24 '17 at 13:38
  • @MajidFouladpour On both occasions it displays [object Object] as result. Assuming you mean to skip the JSON.stringify. – Zarkaylia Jan 24 '17 at 13:44
  • 1
    No, I don't. I mean, if you inspect the value of `result` in the console (F12 > Sources, then set a *breakpoint*), what do you see? – Majid Fouladpour Jan 24 '17 at 13:48
  • @MajidFouladpour result = Object {Search: Array[10], totalResults: "170", Response: "True"} from OMDb. result = Object {data: Array[1], meta: Object, pagination: Object} from Giphy. – Zarkaylia Jan 24 '17 at 14:02
  • 1
    What you have posted in the above comment is a *summary* of the data, not the data itself. Your main complaint as you say is you don't know how to consume the `result` object to add dynamic html to the page. Without providing a sample of the said `result` in your question, how could we help you? Please add a sample of the data you get from the API. – Majid Fouladpour Jan 24 '17 at 14:12
  • @MajidFouladpour Very good and fair point, I've added the result I'm dealing with to the post. – Zarkaylia Jan 24 '17 at 14:21
  • There you have it! @Dexter0015 provides the code that could get you the results you're looking for (for the titles at least). – Majid Fouladpour Jan 24 '17 at 15:18

1 Answers1

4

Both APIs return you a JSON object.

A json object is generally construct like so:

{
    "property1": "value1",
    "property2": "value2"
    "property_array": ["arrayValue1", "arrayValue2"],
    "property_object": {
        "propertyA": "valueA",
        "attributeB": "valueB"
    }
}

So let use OMDb (for example):

to access the results, you need to acces the "Search" attribute :

var entries = result.Search;

Then, you need to "loop" on each property of the Search object (whitch is also an object) :

to do so, you can use a for...in loop:

for(var entry_key in entries) {
    // control that property is own by the object (not prototype)
    if(entries.hasOwnProperty(entry_key)) {
        // do whatever you want with the entry
        // To access the entry, use this notation:
        var entry = entries[entry_key];
        // to stay with OMDb example, this should be: 
        var movie_title = entry.Title;
    }
}

var results = {
    "Search": [{
        "Title": "Titanic",
        "Year": "1997",
        "imdbID": "tt0120338",
        "Type": "movie",
        "Poster": "https://images-na.ssl-images-amazon.com/images/M/MV5BZDNiMjE0NDgtZWRhNC00YTlhLTk2ZjItZTQzNTU2NjAzNWNkXkEyXkFqcGdeQXVyNjUwNzk3NDc@._V1_SX300.jpg"
    }, {
        "Title": "Titanic II",
        "Year": "2010",
        "imdbID": "tt1640571",
        "Type": "movie",
        "Poster": "https://images-na.ssl-images-amazon.com/images/M/MV5BMTMxMjQ1MjA5Ml5BMl5BanBnXkFtZTcwNjIzNjg1Mw@@._V1_SX300.jpg"
    }, {
        "Title": "Titanic: The Legend Goes On...",
        "Year": "2000",
        "imdbID": "tt0330994",
        "Type": "movie",
        "Poster": "https://images-na.ssl-images-amazon.com/images/M/MV5BMTg5MjcxODAwMV5BMl5BanBnXkFtZTcwMTk4OTMwMg@@._V1_SX300.jpg"
    }, {
        "Title": "Titanic",
        "Year": "1953",
        "imdbID": "tt0046435",
        "Type": "movie",
        "Poster": "https://images-na.ssl-images-amazon.com/images/M/MV5BMTU3NTUyMTc3Nl5BMl5BanBnXkFtZTgwOTA2MDE3MTE@._V1_SX300.jpg"
    }, {
        "Title": "Raise the Titanic",
        "Year": "1980",
        "imdbID": "tt0081400",
        "Type": "movie",
        "Poster": "https://images-na.ssl-images-amazon.com/images/M/MV5BMTY5MTQwNzMxNV5BMl5BanBnXkFtZTcwMzkwOTMyMQ@@._V1_SX300.jpg"
    }, {
        "Title": "The Legend of the Titanic",
        "Year": "1999",
        "imdbID": "tt1623780",
        "Type": "movie",
        "Poster": "https://images-na.ssl-images-amazon.com/images/M/MV5BMjMxNDU5MTk1MV5BMl5BanBnXkFtZTgwMDk5NDUyMTE@._V1_SX300.jpg"
    }, {
        "Title": "The Chambermaid on the Titanic",
        "Year": "1997",
        "imdbID": "tt0129923",
        "Type": "movie",
        "Poster": "https://images-na.ssl-images-amazon.com/images/M/MV5BMWUzYjgyNDEtNTAyMi00M2JjLTlhMzMtMDJmOGM1ZmYzNzY4XkEyXkFqcGdeQXVyMTA0MjU0Ng@@._V1_SX300.jpg"
    }, {
        "Title": "In Search of the Titanic",
        "Year": "2004",
        "imdbID": "tt1719665",
        "Type": "movie",
        "Poster": "https://images-na.ssl-images-amazon.com/images/M/MV5BMTAzNjY0NDA2NzdeQTJeQWpwZ15BbWU4MDIwMzc1MzEx._V1_SX300.jpg"
    }, {
        "Title": "Titanic",
        "Year": "1943",
        "imdbID": "tt0036443",
        "Type": "movie",
        "Poster": "https://images-na.ssl-images-amazon.com/images/M/MV5BMTU2Njg4MDgxN15BMl5BanBnXkFtZTcwNzE4MjYyMQ@@._V1_SX300.jpg"
    }, {
        "Title": "S.O.S. Titanic",
        "Year": "1979",
        "imdbID": "tt0079836",
        "Type": "movie",
        "Poster": "https://images-na.ssl-images-amazon.com/images/M/MV5BMTMwOTU5MDU0OV5BMl5BanBnXkFtZTcwMDc4OTYyMQ@@._V1_SX300.jpg"
    }],
    "totalResults": "170",
    "Response": "True"
};


var movies_list = document.getElementById('movies-list');

var entries = results.Search;

for(var entry_key in entries) {
 // control that property is own by the object (not prototype)
 if(entries.hasOwnProperty(entry_key)) {
  // do whatever you want with the entry
  // To access the entry, use this notation:
  var entry = entries[entry_key];
  // to stay with OMDb example, this should be: 
       var movie_line = '<p><strong>Title:</strong> ' 
                      + entry.Title + ' (year: ' + entry.Year + ')</p>';
    movies_list.innerHTML += movie_line;
 }
}
<div id="movies-list">
</div>
Dexter0015
  • 1,029
  • 9
  • 14