treehouse : what would you like to learn today?
Web Design Web Development iOS Development

I Don't Get Asynchronous Updates

  • So this code gets the latest ten dog photos from Flickr using jquery and json. But, how do I get it auto updating when a new photo is available (like twitter search). What are the steps involved?

    <script type=\"text/javascript\" src=\"http://ajax.googleapis.com/ajax/libs/jquery/1.3/jquery.min.js\"></script>

    <script type=\"text/javascript\">
    $(document).ready(function(){
    $.getJSON(\"http://api.flickr.com/services/feeds/photos_public.gne?tags=dog&tagmode=any&format=json&jsoncallback=?\",
    function(data){
    $.each(data.items, function(i,item){
    $(\"<img/>\").attr(\"src\", item.media.m).appendTo(\"#images\");
    if ( i == 9 ) return false;
    });
    });
    });
    </script>

    <div id=\"images\"></div>
  • Kinda simple, all you have to do is wrap the ajax call in a function and name it and call a setInterval() call like the following


    <script type=\"text/javascript\">
    $(document).ready(function(){

    var getFlickr = function(){
    $.getJSON(\"http://api.flickr.com/services/feeds/photos_public.gne?tags=dog&tagmode=any&format=json&jsoncallback=?\",
    function(data){
    $.each(data.items, function(i,item){
    $(\"<img/>\").attr(\"src\", item.media.m).appendTo(\"#images\");
    if ( i == 9 ) return false;
    });
    });
    }
    setInterval('getFlickr', 3000);
    });
    </script>

    every 3 seconds


    Second way to do it though more dirty is to wrap the entire code in the setInterval() like so


    <script type=\"text/javascript\">
    $(document).ready(function(){

    setInterval(function(){
    $.getJSON(\"http://api.flickr.com/services/feeds/photos_public.gne?tags=dog&tagmode=any&format=json&jsoncallback=?\",
    function(data){
    $.each(data.items, function(i,item){
    $(\"<img/>\").attr(\"src\", item.media.m).appendTo(\"#images\");
    if ( i == 9 ) return false;
    });
    });
    }, 3000);

    });
    </script>




    Either way the function has 2 parameters setInterval(function, time)
    note that the time is set in ms (3000 = 3 seconds, 500 = 1/2 a second, ect)