How do I get my search box connected with the Rotten Tomatoes API so I can do a search in my web page and it returns the results from Rotten Tomatoes?
I added the $userSearch
variable in the PHP section. And I put that variable in the urlencode
function. I am a bit lost on how to proceed. I think I need to use AJAX jQuery, do I need to create a JavaScript file that contains the code to hit the API and have an "action" inside my search box definition? I am a bit confused on how to go about this and am having trouble finding an example. I am building this off the
Rotten Tomatoes PHP Example.
Here is my code with a "Mouse" search hard coded:
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title></title>
</head>
<body>
<form method="post" action="www.websitehere.com/folderhere/"
name="searchform" id="searchform">
<label for="Search"> Search: </label>
<input type="text" id="search" name="myName" placeholder="Search for movie"
required="required" style="width: 520px" />
<label for="category" id="category">Category</label>
<select>
<option value="title" selected="selected">Movie Title</option>
<option value="director">Director</option>
<option value="genre">Genre</option>
</select>
<input type="submit" value="Search" id="searchbtn">
<input type="submit" value="Add" id="searchbtn">
<p></p>
<div id="search_results">Local Search results</div>
</form>
<?php
$userSearch = 'Mouse';
$apikey = 'myapikeyhiddenforprivacy';
$q = urlencode($userSearch); // make sure to url encode an query parameters
// construct the query with our apikey and the query we want to make
$endpoint = 'http://api.rottentomatoes.com/api/public/v1.0/movies.json?apikey=' . $apikey . '&q=' . $q;
// setup curl to make a call to the endpoint
$session = curl_init($endpoint);
// indicates that we want the response back
curl_setopt($session, CURLOPT_RETURNTRANSFER, true);
// exec curl and get the data back
$data = curl_exec($session);
// remember to close the curl session once we are finished retrieveing the data
curl_close($session);
// decode the json data to make it easier to parse the php
$search_results = json_decode($data);
if ($search_results === NULL)
die('Error parsing json');
// play with the data!
$movies = $search_results->movies;
echo '<ul>';
foreach ($movies as $movie) {
echo '<li><a href="' . $movie->links->alternate . '">' . $movie->title . " (" . $movie->year . ")</a></li>";
echo '<img src="' . $movie->posters->detailed . ' "/><br>';
}
echo '</ul>';
?>
</body>
</html>
There is no need for PHP in this scenario. Why make an AJAX call to your server side code to make a call to the API when you can call to the API directly from JavaScript?
Take a look at the example JavaScript code on the page you shared a link to:
http://developer.rottentomatoes.com/docs/read/json/v10/examples#JavaScript