Let's wrap it up:
Html, Css, javascript, Jquery, and API's!

A simple primer, Prepared by Zoe F

Setting up the HTML structure

  • Create a new .html document called moviegrabber.html and save it somewhere safe in your harddrive.
  • Let's start by turning this into a classic webpage to hold our new app. Give it html tags, head tags, and body tags. Make sure you're using good nesting practices.
  • Now, let's give ourselves some content! In the body, let's make a div for the action to happen in. Let's give it an ID attribute of "movieForm" so that our CSS and Javascript can find it.
  • Let's put some content in that div. For now, let's insert the phrase "Give me a movie name!" inside of it. Then let's wrap that text in h1 tags so that it looks nice, and give ourselves some room underneath it with a line break. You can use a br tag right after the closing h1 tag.

Formatting it with CSS

  • Let's make the page look pretty with some simple css! Because this is so basic we don't need a separate css file, let's just put it right in the head. Set up the css definition area in the head section with some style tags
  • First let's give our body tag a background color. In our style section in the head, let's define our body tag to have a background color of light yellow. You can use the one below, or pick another color hex code.
  • <style>
       body {background-color: #ffffcc;}
  • Now, let's put some formatting on our div! Using the ID we gave it, movieForm, let's give it a width, padding, border, background color, and an alignment for its text. Let's also center the whole div using a margin trick: if the left and right margins are both set to "auto" it will automatically center the div.
  • #movieForm {
              border: 2px solid #F3F; 
              margin:10px auto;



Adding Javascript

  • Let's make this page reactive to our will! First let's give our users an area to interact with. Inside our div, just after our BR, let's add two different types of inputs. The first is of type "text", which stands for a text input feild, so that users can enter in the name of the movie they want to search for! Let's also give this input an ID of movieTitleID so that our javascript will be able to grab whatever our users enter! Then let's add a linebreak right afterwards.
    Enter a Title: <input id="movieTitleID" type="text"><br>
  • Now we need a second area for users to interact with, this time tell us when they're ready to submit their info. Let's add a second input tag, this time of type "submit" so that it looks like a button. Let's give it a value of "Do it" so that users know what its for.
     <input value="Do it!" type="submit">
  • Let's make a javascript function for our new button to call! We're going to name our function "runThatQuery", and we want it to run when the user clicks the button. Let's add an onClick attribute to our button input, inside the input tag, that calls runThatQuery. Remember that putting () after a peice of javascript means we're calling a function. Now, whenever the button is clicked, our new function runThatQuery() will be called
  • Let's tell our page what to do when the button is clicked by defining that new function with some javascript! But before we do, let's get together all the resources we need. We don't want to recreate functions that other programmers have already made for us, so we'll be using some existing JQuery functions, and we'll also be creating a couple of our own functions.

    First, let's include the Jquery library file in our html. Remember, a library is just a .js file with a bunch of premade functions in it. You could make one yourself if you want! The JQuery library is big enough that we probably don't want to bother downloading it and saving it. So instead, we'll link to it where there's a copy hosted by Google.

    Look up the most recent version of JQuery hosted by google (linked at right if you don't want to search for it). Then put the snippet that includes it in our file in the head, after the close of our style tag. Make sure you're including the whole url, including http://. If the version was 1.11.0, it would look like this:
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>
  • Now, let's give our own javascript functions somewhere to live. Create a new javascript file called "woohoo.js" and save it to the same folder where you saved your moviegrabber.html file. Then, we need to tell our HTML where to look for it. Include that file in the head of our html page just below our jquery include.
    <script src="woohoo.js"></script>
  • Lastly, let's check to make sure everything is talking to each other! In woohoo.js, let's give our function runThat Query a simple definition. Let's make it do just one thing, output the phrase "This function is totally working!" to the console.
    function runThatQuery() {
        console.log ("This runThatQuery function is totally working!");
  • Open up your console in Chrome and make sure that your html and .js files are communicating with each other when you click the button.


jQuery on google

jQuery functions

console.log ()

Stuck? Can't fix it? Already tried the 1-minute rule? Then have an HTML Check-in

Querying the API

  • Let's give this function some...functionality. We're going to use the OMDB API which is one of a number of API's for the Internet Movie Database. The first thing we need to do when querying the OMDB API is to create the API call that will give us the information we need. Inside our runThatQuery function, after our console.log test, lets set up some variables to hold the the parts of our api call. First, let's set the base url. Let's make a variable to hold it called baseURL, so we can remember it easily. Check the OMDB reference at right to make sure you're using the right one. It should look like this.
    var baseUrl = "http://www.omdbapi.com/?";      
  • Next, let's set up our query. We'll want to read in the value from the moveiTitleID input field we created in our HTML page. We're going to use Jquery's "val" function for that. Remember, the "$" tells javascript this is coming from the jquery library, not just standard javascript, which would require a lot more code. Let's create a new variable called searchQuery to hold what we get from it!
    var searchQuery = $( "#movieTitleID" ).val();
  • OMDB doesn't require an API key (although at one time, it's other 'Posters' API did)! But if it did require a key, this would be a good time to register for one! We would want to save that API key into a variable so that we could concatinate it into our search query. Luckily we don't have to!

    We're all ready to make our API call! We're going to use a Jquery function called Ajax to do it for us. This will allow us to load in our results fast, without having to reload the entire page. The nice thing about ajax is that we can set up the parameters right inside of our own function- kind of like a function inside a function.

    Ajax needs three parameters to work - the url we're going to call (including the query itself), the datatype of the information we want to get back, and what to do if it succeeds!

    Let's do it! First, let's set up the ajax function itself, right below our last variable, still inside our function definition.
          //stuff in here!
  • Now, inside that ajax call, let's set up our three parameters. First, let's create our url from the variables we defined above, plus our arguments. If you check the OMDB API reference, we'll see that to add our query from the user's input feild, we'll use the argument "s=" to tell the api what to look for! It stands for "Search" (As opposed to "t=" which would only give us exact title matches.

    And remember, all arguments in an API call get separated by an & symbol.

    We're also going to use another built-in function called "encodeURI" to convert characters the user might have typed that can't be included in a url, like spaces and percent signs. That way, if someone searches for "Dark Knight" we'll still be able to send it.

    Let's do it. We're going to take our base URL, and concatenate it with the type of query we want to make, and concatenate THAT with our encoded search string. Note the use of coma's here. This is our first parameter inside our Ajax call:
    url: baseUrl + '&s=' + encodeURI(searchQuery),
  • Now, let's set the type of data we want back. We're going to ask for a variation of JSON, called JSONP which allows us to make calls from a browser without having to mess around with all kinds of security stuff.
    dataType: "jsonp",
  • Finally, we need to tell ajax what to do when it's all done! Otherwise we'll have this great data but we might never know. On success, we want ajax to call another function with the info it's collected. We could define that function right here just like we did with ajax, but then we'd have a function inside a function inside a function, which is pretty complicated. Let's have it call an external function we'll create called "searchCallback" which we'll define in a moment.
    success: searchCallback
  • The last thing we need to do is test that all our pieces are working right! Below our runThatQuery function, after its final closing curly bracket, let's create a brand new function to test. It will be called every time Ajax is successful. Let's call it searchCallback() and let's have it accept one parameter, data. That means Ajax can send it any data it succeeds in collecting.
    function searchCallback(data) {      
  • To test if our new function is working, and communicating with our ajax, let's put a test inside this function.
    console.log("Ajax found some results, and now we are in searchCallback!!"); 
    Run it in Chrome and test to make sure everything is working!




Stuck? Can't fix it? Already tried the 1-minute rule? Then have a javascript Check-in

Displaying JSON results

  • Everything's talking to each other, so now let's do something with the JSON results we're getting back. First, let's take a look at what they look like so we know our options!

    Notice in searchCallback that the info we're getting back is being saved into a variable called "data". We can use that! In your searchCallback function, below the console.log test, let's make a second console.log which dumps the data variable we just passed out to the screen. That way we can se it!. Let's use a built-in function called stringify() which takes the whole JSON file and turns it into one long string so that we can read it.
    console.log (JSON.stringify(data));
    Test it in the console! Use a search query you know works, like "Frozen" or "Usual Suspects"
  • Wow, this is a whole lot of data, but when we look closely at this long String, we can see some of the categories of info available to us. We have access to the total number of movies that match our query, and we also have, for each movie, access to theirTitle,Year, imdbID,Type, and Poster if it has a url! Let's print some of this information out to the user's screen.

    First, let's tell the user how many results there were to their query. Let's use jquery to replace the content inside our div (the one with the id movieForm) with our results.

    We're going to use a jquery function called html(), which literally replaces the html inside the element with the id we want with some new html. But how do we get that total number? When we look at the output of our console.log, notice at the end of our string, that the overall number of results in the data variable we're using is denoted by the word totalResults. To get the information in the total data variable of result we can just use data.totalResults.
     $("#movieForm").html('I Found ' + data.totalResults + ' results total!<BR>');
    Test it out! Perhaps change the formatting a little - maybe this would look better in a larger <H1> size?
  • Looking good! Now, let's get the list of movie titles in our results. Look at the JSONP string. the list of movies is denoted with the label Search. Let's create a variable called myMovies to hold all the movies we've got listed here in our data variable, inside the Search list. Incidently, this variable we're creating, movies, is called an "array" - it's a list of items. Let's do it. In the data variable, let's take the list of movies in Search, and assign it to our variable, movies.
    var movies = data.Search;
  • Next, let's use a jquery each() function which acts like a loop to go through the myMovies variable list. We'll define the each() function so that for every item in the list we're going to use the append() function to add a snippet of html into our div with id movieForm. That html will contain the title, and the thumbnail form that movie. Check the JSON readout to make sure you're using the right variable names.
    $.each(movies, function(index, movie) {
    $("#movieForm").append('<h3>' + movie.Title + '</h3><img src="' + movie.Poster + '">'); });
    Test it out. You should now be bringing in all the result names and images.
  • Now try displaying the year for each as well.

    BONUS: If the year is after 2010, make the it red to show it's hot! Otherwise, make it blue.

    BONUS BONUS: Notice that sometimes old or lesser-known movies have no poster, which leads to a "broken" image in the list. Fix it! When there's no poster, either show a default graphic or show no poster at all.



Stuck? Can't fix it? Already tried the 1-minute rule? Then have a javascript Check-in