I'm going through a learning project for myself and trying to build a bad movie suggestion generator that returns 6 random movies based on their ratings being 4 stars or less. I've gotten able to return a random results page and a single random item inside that page, but I can't seem to get it to do the process multiple times. Is there any way to do this?
var rand = Math.floor(Math.random() * 20);
var randPg = Math.floor(Math.random() * 17);
var settings = {
"async": true,
"crossDomain": true,
"url": "https://api.themoviedb.org/3/discover/movie?vote_average.lte=4&vote_count.gte=25&page=" + randPg + "&include_video=false&include_adult=false&sort_by=popularity.asc®ion=US&language=en-US&api_key=XXXXXXX",
"method": "GET",
"headers": {},
"data": "{}"
}
$.ajax(settings).done(function (response) {
console.log(response);
console.log(response.results[rand]);
});
Can't find a movie or TV show? Login to create it.
Want to rate or add this item to a list?
Not a member?
Reply by Travis Bell
on May 15, 2019 at 11:25 AM
Hi @markfenske84,
You'll need a counter to iterate over. Something along the lines of this.
Reply by markfenske84
on May 18, 2019 at 2:59 AM
Thanks Travis,
I was making some headway on this project tonight, but then all of a sudden my results object started randomly coming back empty. Everything was working as expected for an hour or so and every refresh was returning the object as expected, but then all of a sudden it just stopped. The object itself keeps returning results - a random page, total_results, total_pages, but then the results array object will sometimes be empty and sometimes have data. Seems to be totally random when it will work and when it won't. The basics of the code from above is all the same, except I have this inside the ajax function:
When I console.log(response), sometimes I get something along these lines: {page: 16, total_results: 49, total_pages: 3, results: Array(0)}, and other times I get something like this: {page: 2, total_results: 49, total_pages: 3, results: Array(20)}. Obviously when I get Array(0), the movieObj variable for results comes back as undefined and the script breaks. If it comes back populated with data, then it works. Can't figure out why it stopped working?
EDIT: I found out what was causing the break but not why it's happening. When I change the param of vote_average.lte= from 4 to 3, then getting a results Array back populated is completely random. If it's set to 4, it works fine.