Using AJAX to Extract Data from IMDB API
Asked Answered
C

1

1

I'm trying to get the year of a film given its title using IMDB's API and then appending the year in parenthesis next to the title.

There's some fundamental JS or AJAX thing that I'm screwing up. Any help would be much appreciated!

This is my code: jsFiddle

HTML

<ol>
    <li>Jaws</li>
    <li>The Lord of the Rings</li>
</ol>

jQuery

function getYear(title)
{
    $.ajax({
      url: "http://www.imdbapi.com/?t=" + title,
        dataType: 'jsonp',
        success: function(data){
            var year = data.Year;
        }
    });

}

$("li").each(function() {
      var text = $(this).text();
      getYear(text);
      $(this).append(" ("+year+")");
});
Concessive answered 31/1, 2014 at 7:12 Comment(2)
possible duplicate of How to return the response from an AJAX call?Aracelyaraceous
Here's an updated fiddleKnownothing
K
1

Your code is calling the AJAX function, but immediately going on to update the page before the asynchronous function returns. You need to include the code that updates the page in the callback to the AJAX function so that it executes when the data is ready.

I have reworked your code to this:

function getYear(title)
{
    $.ajax({
      url: "http://www.imdbapi.com/?t=" + $(title).text(),
        dataType: 'json',
        success: function(data){
            var year = data.Year;
            var text = $( this ).text();
            $(title).append(" ("+year+")");

        }
    });

}

$( "li" ).each(function() {

      getYear(this);
});

Which works successfully on this fiddle

Knownothing answered 31/1, 2014 at 7:34 Comment(2)
Thank you, that makes total sense now that you say it like that.Concessive
I'm getting having "Cross-Origin Request Blocked" when attempting to use this solution It does seem to work if I use this site OMDBapi thoughTinware

© 2022 - 2024 — McMap. All rights reserved.