shuchi shuchi - 6 months ago 80
jQuery Question

OMDb API not working in javascript

I am using OMDb API to fetch Title, Year and Runtime of movie. These should appear on the page as soon as it loads.I used j query ajax for this. But it does not work.

As soon as the page loads it shows undefined written there. Where I am making the mistake??

I am new to j query ajax and API's so any help would be appreciated.Thanks in advance :)



<! doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">

<!-- Latest compiled and minified JavaScript -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js">< </script>

<script type="text/javascript">

window.onload=function()
{
$.ajax({
url: "http://www.omdbapi.com/?t=spiderman&y=&plot=full&r=json",
crossDomain: true,
dataType: "json",
success: fetch
});
}
//For fetching data on success
function fetch(e){
var result="";
$.each(e,function(value){

result+="<p>" +value.Title +"</p>";
result+="<p>" +value.Year +"</p>";
result+="<p>" +value.Runtime +"</p>";

});
$('#movie').html(result); //For storing result in html
}
</script>

</head>

<body>
<p id="movie"></p>

</body>




hsh hsh
Answer

looping inside returned value is wrong,the returned json looks like this:

{"Title":"Spiderman","Year":"1990","Rated":"N/A","Released":"N/A","Runtime":"5 min","Genre":"Short","Director":"Christian Davi","Writer":"N/A","Actors":"N/A","Plot":"N/A","Language":"German","Country":"Switzerland","Awards":"N/A","Poster":"N/A","Metascore":"N/A","imdbRating":"5.7","imdbVotes":"90","imdbID":"tt0100669","Type":"movie","Response":"True"}

so just call e.Title to get title and so on:

<! doctype html>
	<html lang="en">
<head>
		<meta charset="utf-8">
		<meta http-equiv="X-UA-Compatible" content="IE=edge">
		<meta name="viewport" content="width=device-width, initial-scale=1">

 <!-- Latest compiled and minified JavaScript -->
<script      src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"><  </script>
   
<script type="text/javascript">
		
		window.onload=function()
    {
	 $.ajax({
        url: "http://www.omdbapi.com/?t=spiderman&y=&plot=full&r=json",
        crossDomain: true,
        dataType: "json",
        success: fetch
    });	
}
    //For fetching data on success
   function fetch(e){      
	   var result="";
       result+="<p>Title: " +e.Title +"</p>"; 
       result+="<p>Year: " +e.Year +"</p>";
       result+="<p>Run Time:" +e.Runtime +"</p>";	 
	   
	   $('#movie').html(result); //For storing result in html
   }			
</script> 
 
</head>
      
<body>
  <p id="movie"></p>
  
 </body>

Comments