Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Calling "imdbapi.com" with jquery

Tags:

jquery

ajax

I'm trying to get the movie poster from IMDB according to the title of a movie, in a function.

I have tried :

function getPoster(title)
{
    $.ajax({
      url: "http://www.imdbapi.com/?t=" + title,
      datatype: "json",
      success: return data
    });
}

But I don't really know how to "return" data I got from .ajax() ...

edit IMDBapi returns a json dataset, as in :

{"Title":"Jurassic Park","Year":"1993","Rated":"PG-13","Released":"11 Jun 1993","Genre":"Action, Adventure, Family, Sci-Fi","Director":"Steven Spielberg","Writer":"Michael Crichton, Michael Crichton","Actors":"Sam Neill, Laura Dern, Jeff Goldblum, Richard Attenborough","Plot":"During a preview tour, a theme park suffers a major power breakdown that allows its cloned dinosaur exhibits to run amok.","Poster":"http://ia.media-imdb.com/images/M/MV5BMTc2NDIxNTQyNF5BMl5BanBnXkFtZTcwNzIwMzM3MQ@@._V1._SX320.jpg","Runtime":"2 hrs 7 mins","Rating":"7.9","Votes":"159458","ID":"tt0107290","Response":"True"}

edit2 : This worked :

for(var i in titles)
{
    $.ajax({
      url: "http://www.imdbapi.com/?t=" + titles[i],
      dataType: 'jsonp',
      success: function(data) {
        $('body').append(data.Poster+'<br />');
      }
    });
}
like image 539
Manu Avatar asked Jun 07 '11 13:06

Manu


2 Answers

You can't.

AJAX is asynchronous; you only get a reply from the server after your function returns.

Instead, you can make your function accept a callback, just like $.ajax does.

like image 199
SLaks Avatar answered Sep 30 '22 02:09

SLaks


You could do:

function getPoster(title)
{
    $.ajax({
      url: "http://www.imdbapi.com/?t=" + title,
      datatype: "jsonp",
        success: function(data){
            console.log(data);  
            do_some_function(data);
        }
    });

}

Demo: http://jsfiddle.net/xVAbm/2/

like image 36
Naftali Avatar answered Sep 30 '22 03:09

Naftali