JavaScript JSON


This JSON example was presented at the October 8, 2014 hands-on lab by Bill Wolff. This demonstrates a simple query to Flickr that returns links in a JavaScript array via JSON. jQuery is used to fetch the results and create the DOM elements.

To recreate this, create a new web page in your favorite editor. Microsoft WebMatrix was used during the lab. Open a browser to http://getbootstrap.com. Use the Getting Started menu link. On the right nav, click Basic Template. Copy the code and paste into your editor. This code expects the Bootstrap and jQuery files to be stored on your web site. To keep things simple, use a CDN instead (content delivery network). Click the download link in the right panel navigation on the Bootstrap site. Copy the CDN lines and replace the matching lines on the Basic Template. You now have a working HTML page with both Bootstrap and jQuery ready for testing.

The <div> at line 17 introduce the Bootstrap container, jumbotron, and button classes. Add these and test.

The <div> at line 27 is a placeholder with an ID that is used to add images to the DOM in jQuery.

The <script> at line 33 creates a JavaScript SEAF (self executing anonymous function) that runs as soon as the page loads. It uses the jQuery getJSON() helper method to call the Flickr API and get a list of pictures using a search tag. Note the filter tags could be inserted directly into the URL but they are easier to read and maintain in the method parameter array. When this function completes, the .done function is called (we are doing a JSONP callback). The function takes a data parameter that has the query results already converted from the response text to a JavaScript object which is similar to doing a JSON.parse(). The .each iterates over the data array and uses jQuery syntax to create <img> elements inside <div> elements. The <img> get their src and title attributes from the Flickr result data. Both <img> and <div> add Bootstrap classes to make a pleasing layout that is responsive on smartphones and tablets. The i === 3 line limits the number of pictures. Set this to 3, 7, 11 or any other number up to 20 to see what happens. By default, Flickr returns 20 image links each time and will randomly change the results on each refresh. Change the tags: ‘phillydotnet’ to another term to see your favorite pictures.

<!DOCTYPE html>

<html lang="en">
    <head>
        <meta charset="utf-8">
        <meta http-equiv="X-UA-Compatible" content="IE=edge">
        <meta name="viewport" content="width=device-width, initial-scale=1">
        <title>JSON Lab Sample</title>
        <!-- Latest compiled and minified CSS -->
        <link rel="stylesheet"
            href="http://maxcdn.bootstrapcdn.com/bootstrap/3.2.0/css/bootstrap.min.css">
        <!-- Optional theme -->
        <link rel="stylesheet"
            href="http://maxcdn.bootstrapcdn.com/bootstrap/3.2.0/css/bootstrap-theme.min.css">
    </head>
    <body>
        <div class="container">
            <div class="jumbotron">
              <h1>philly.NET Labs</h1>
              <p>Every first Wednesday of the month at Microsoft in Malvern, PA</p>
              <p><a id="learn"
                    href="http://phillydotnet.org/labs"
                    class="btn btn-primary btn-lg"
                    role="button"
                    title="Show me the labs!">Learn more</a></p>
            </div>
            <div id="images" class="row"></div>
        </div>
        <!-- jQuery (necessary for Bootstrap's JavaScript plugins) -->
        <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
        <!-- Latest compiled and minified JavaScript -->
        <script src="http://maxcdn.bootstrapcdn.com/bootstrap/3.2.0/js/bootstrap.min.js"></script>
        <script>
            (function () {
                var flickerAPI = "http://api.flickr.com/services/feeds/photos_public.gne?jsoncallback=?";
                $.getJSON(flickerAPI, {
                    tags: "phillydotnet",
                    tagmode: "any",
                    format: "json"
                })
                .done(function (data) {
                    //alert(JSON.stringify(data));
                    $.each(data.items, function (i, item) {
                        $("<div>")
                        .addClass("col-md-3")
                            .append($("<img>")
                                        .addClass("img-thumbnail")
                                        .attr("src", item.media.m)
                                        .attr("title", item.title)
                            ).appendTo("#images");
                        if (i === 3) {
                            return false;
                        }
                    });
                });
            })();
        </script>
    </body>
</html>