Search code examples
javascriptjqueryajaxjsonrotten-tomatoes

Why is this $.ajax function successful only the second time it's called?


I'm experimenting with the Rotten Tomatoes API. On a click event, a search returns JSON data for the closest matched movie title and thumbnail image to the search input.

Upon completion of that first $.ajax request, a second $.ajax request is made, using var resultID, which was declared at the top and set upon 'success' of the first $ajax request.

As of now, when I click for the first time, it runs the first request successfully, but it can't run return json.total (upon 'complete') because the resultID is returned as 'undefined'. But the second time I click, resultID has apparently been set, since it will return json.total successfully.

I'm guessing this a simple problem related to how I'm declaring and calling resultID (or the asynchronous firing of ajax), but I'm not sure what it is. Can anyone explain?

var apiKey = '***********';
var resultID = "";

$('#search-submit').click(function(){
    var queryText = $('#movie-search').val();
    var queryURI = encodeURI(queryText);
    var searchApiRequest = "http://api.rottentomatoes.com/api/public/v1.0/movies.json?q=" + queryURI + "&page_limit=10&page=1&apikey=" + apiKey;
    var reviewApiRequest = "http://api.rottentomatoes.com/api/public/v1.0/movies/" + resultID + "/reviews.json?review_type=top_critic&page_limit=10&page=1&country=us&apikey=" + apiKey;

    $.ajax({
        url: searchApiRequest,
        type: 'GET',
        dataType: 'jsonp',
        error: function() {
            console.log('there was error in processing the search request.');
        },
        success: function(json) {
            var movieInfo = json.movies[0];
            var noResultsMessage = 'your search returned no matches. Please try again.'; 
            var resultTitle = movieInfo.title;
            var resultThumb = movieInfo.posters.thumbnail;
            var resultDesc = movieInfo.critics_consensus;

            var reviewsPublicURL = movieInfo.links.reviews;
            var reviewsRequest = reviewsPublicURL;

            resultID = movieInfo.id; // supposed to set global var resultID to movieID

            $('.search-results').find('img').attr('src',resultThumb).end().find('h1').text(resultTitle).end().find('p').text(resultDesc);

        },
        complete: function() {
            $.ajax({
                url:reviewApiRequest,
                type: 'GET',
                dataType: 'jsonp',
                error: function(json) {
                    console.log('for whatever reason, we could not find any reviews of this movie');
                },
                success: function(json) {
                    console.log(json.total);
                } 
            });
        }
    });
});

Solution

  • You need to not only set a global resultID but also refresh a reviewApiRequest as well. It doesn't magically change its value by itself when you update resultID.