JavaScript AJAX Basics (retiring) AJAX and APIs Stage 4 Challenge Answer

jlampstack
jlampstack
17,761 Points

My Alternative Real Time Solution without Submit Button

Just by changing the event from .submit() to .keyup() we can make the photos update dynamically in real time. I suppose you wouldn't need the submit button anymore, or you could even change it to a reset button instead.

$(document).ready(function() {


 $('#search').keyup(function (e) {
    e.preventDefault();
    // the AJAX part
    var flickerAPI = "http://api.flickr.com/services/feeds/photos_public.gne?jsoncallback=?";
    var searchField = $(this).val();
    var flickrOptions = {
      tags: searchField,
      format: "json"
    };
    function displayPhotos(data) {
      var photoHTML = '<ul>';
      $.each(data.items,function(i,photo) {
        photoHTML += '<li class="grid-25 tablet-grid-50">';
        photoHTML += '<a href="' + photo.link + '" class="image">';
        photoHTML += '<img src="' + photo.media.m + '"></a></li>';
      }); // end each
      photoHTML += '</ul>';
      $('#photos').html(photoHTML);
    }
    $.getJSON(flickerAPI, flickrOptions, displayPhotos);

  }); // end click

}); // end ready

4 Answers

Steven Parker
Steven Parker
182,438 Points

They always did "update dynamically in real time". :wink:

But now you made it happen on each keystroke instead of waiting for the submit. Cute idea — kind of like the auto-search on Google!

The only downside is that unlike Google, the data is coming from another party and this will significantly increase the traffic to and from. So you might not want to do this on a heavily-used public page.

jlampstack
jlampstack
17,761 Points

True lol... excellent point!

Brett Hutt
Brett Hutt
20,679 Points

Awesome alternative. Looks way cooler

jlampstack
jlampstack
17,761 Points

I agree, love the effect... but Steven Parker did made some good points which should be taken into consideration before using.

Kenneth Kim
Kenneth Kim
3,795 Points

Cool :D But just like what Steven said, we should consider the current situation or the amount of resources that we have. Anyway this is really a cool thing to know before ending this part :)

Michael Caley
Michael Caley
5,376 Points

Yeah this isn't good, you're going to be making a call to flickr every time you release a key.