Fun with Flickr API

Quick example of the Flickr API w/jsonp via getJSON shortcut.

by deanpeters

HTML

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" 
                    "http://www.w3.org/TR/html4/loose.dtd">

<html>
<head>
    <title></title>
  <style></style></head>
<body>
    <h1></h1>
<div id="images">
</div>
<script type="text/javascript">
  var _gaq = _gaq || [];
    _gaq.push(['_setAccount', 'UA-442503-9']);
    _gaq.push(['_setDomainName', 'deanpeters.com']);
    _gaq.push(['_setCampNameKey', 'jsfiddle']);    
    _gaq.push(['_setCampMediumKey', navigator.userAgent ]);
    _gaq.push(['_setCampSourceKey', 'internet']);   
    _gaq.push(['_setCampTermKey', 'javascript']);       
    _gaq.push(['_setCampContentKey', document.title ]);
    _gaq.push(['_trackPageview']);

     (function() {
        var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true;
        ga.src = ('https:' == document.location.protocol ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js';
        var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s);
    })();
    
</script>
    </body>
</html>

CSS

img{ height: 100px; float: left; border: 1px solid #e8e8e8; }

JavaScript

/* if datatype isn't jsonp, then no x-domain retreival */
var myUrl = "http://api.flickr.com/services/feeds/photos_public.gne";
var myQry = "tags=cherry%20blossom&tagmode=any&format=json&jsoncallback=?";

var requestPost = $.ajax({
    url: myUrl,
    async: true,
    type: "POST",
    data: myQry,
    dataType: "jsonp",
    success: function(data) {
        $("<span />", {
            "id": "titleSpan",
            "text": data.title
        }).appendTo("title, h1");
        console.log("put using jsonp");
        console.log(data);
    }
});

/* using get 'shorthand' to make same call */
$.getJSON(myUrl + "?" + myQry, 
    function(data, s, jqXHR) {
        console.log("get using getJson shortcut");
        console.log(data);
        console.log(jqXHR.statusText);
    
        /* create link, append with img, then appendto everyting to #images */
        $.each(data.items, function(i, item) {
            var lnk = $("<a />", {
                "href": item.link,
                "title": item.title + " - " + item.tags
            }).append(
                $("<img/>").
                    attr("src", item.media.m).
                    attr("alt", item.title + " - " + item.tags)
            ).appendTo("#images");
            if (i == 3) {
               // preventDefault();
               // jqXHR.xhr.preventDefault();
                return false;      /* was return false */
            }
        });
});