Home > Software engineering >  Get IMDB info using JavaScript
Get IMDB info using JavaScript

Time:10-21

I am trying to get IMDB info using JavaScript. The following code is working for Title, Year, IMDB link but when I am trying to get "Runtime", "Director", "Released" etc I am getting as undefined. Please help!

This is the data formate: https://www.omdbapi.com/?i=tt4779682&apikey=ba1f4581

Code:

var data;
function getanswer(q){
$.get("https://www.omdbapi.com/?s=" q "&apikey=ba1f4581", function(rawdata){
var rawstring =JSON.stringify(rawdata);
data =JSON.parse(rawstring);
var title = data.Search[0].Title;
var year = data.Search[0].Year; 
var director = data.Search[0].Director; 
var imdburl="https://www.imdb.com/title/" data.Search[0].imdbID "/";

var posterurl =data.Search[0].Poster;
document.getElementById('answer').innerHTML="<h1>" title "</h1><br> <img src= '" posterurl "'><br><p> Year Released:" year "</p> <br><p> Year Released:" director "</p> <br> <p> IMDB page: <a href='" imdburl "'target='_blank'>" imdburl "</a></p>"; }); }
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<html>
<head></head>
<body onload="getanswer(document.getElementById('qurybox').value)">
<!doctype html> <input value="The Meg" onkeyup="getanswer(document.getElementById('qurybox').value)" id="qurybox"> <div id="answer"></div> 
</body>
</html>
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

CodePudding user response:

According to the api documentation, you were using s parameter that would not return Runtime/Director/etc. You could use the t parameter and remove Search[0].

Below is the code that would work:

var data;
function getanswer(q){
$.get("https://www.omdbapi.com/?t=" q "&apikey=ba1f4581", function(rawdata){
var rawstring =JSON.stringify(rawdata);
data =JSON.parse(rawstring);
console.log(data);
var title = data.Title;
var year = data.Year; 
var director = data.Director; 
var imdburl="https://www.imdb.com/title/" data.imdbID "/";

var posterurl =data.Poster;
document.getElementById('answer').innerHTML="<h1>" title "</h1><br> <img src= '" posterurl "'><br><p> Year Released:" year "</p> <br><p> Year Released:" director "</p> <br> <p> IMDB page: <a href='" imdburl "'target='_blank'>" imdburl "</a></p>"; }); }
  • Related