little page jquery, ajax, json
by Deborah
HTML
<link rel="stylesheet" href="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8/themes/base/jquery-ui.css">
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.5/jquery.min.js"></script>
<script src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8/jquery-ui.min.js"></script>
<section id="fetch" class="form">
<input type="text" placeholder="Enter a title" id="term" class="formField" />
<button id="search">Find poster</button>
</section>
<section id="poster"> </section>
CSS
body {
font-family: Arial;
}
.form {
padding: 1em;
background: #ececec;
}
.formField {
font-size: 1.1em;
padding: 2px;
}
.placeholder {
color: #ff0099;
font-weight: normal;
}
::-webkit-input-placeholder {
color: #cccccc;
}
:-moz-placeholder {
color: #cccccc;
}
:-ms-input-placeholder {
color: #cccccc;
}
:focus::-webkit-input-placeholder {
color:transparent;
}
.content {
margin-top: 5px;
padding: 1em;
background: #eeeeee;
}
JavaScript
// little page jquery, ajax, json
// http://coding.smashingmagazine.com/2012/02/09/beginners-guide-jquery-based-json-api-clients/
// http://jqueryui.com/demos/autocomplete/remote-jsonp.html
$(document).ready(function() {
//This is to remove the validation message if no poster image is present
$('#term').focus(function() {
var full = $("#poster").has("img").length ? true : false;
if (full == false) {
$('#poster').empty();
}
});
var getPoster = function() {
//Grab the movie title and store it in a variable
var film = $('#term').val();
//If the input field was empty, display a message
if (film === '') {
$('#poster').html("<h2>Nothing was entered.</h2>");
} else {
// (validated) field is not empty
$('#poster').html("Loading");
// the long number is the api key that you sign up for as a developer
// MUST append "?callback = ?" to not fail call to external site
$.getJSON("http://api.themoviedb.org/2.1/Movie.search/en/json/23afca60ebf72f8d88cdcae2c4f31866/" + film + "?callback=?", function(json) {
// get the json file into chrome or firebug console so you can look at it
console.log(json);
// if not nothing found, display poster
if (json != "Nothing found.") {
$('#poster').html('<img id="thePoster" src=' + json[0].posters[2].image.url + ' />');
} else {
//If nothing is found, goonies poster
$.getJSON("http://api.themoviedb.org/2.1/Movie.search/en/json/23afca60ebf72f8d88cdcae2c4f31866/goonies?callback=?", function(json) {
console.log(json);
$('#poster').html('Nothing found. Goonies. <br /><img id="thePoster" src=' + json[0].posters[0].image.url + ' />');
});
}
...