Welcome to the Treehouse Community

The Treehouse Community is a meeting place for developers, designers, and programmers of all backgrounds and skill levels to get support. Collaborate here on code errors or bugs that you need feedback on, or asking for an extra set of eyes on your latest project. Join thousands of Treehouse students and alumni in the community today. (Note: Only Treehouse students can comment or ask questions, but non-students are welcome to browse our conversations.)

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and a supportive community. Start your free trial today.

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

live search function working... Buggy?

Hi I tried to get a live search function working which is however acting wierd.. I removed all buttons and forms, leaving only the searchbar and used .keypress() to fire it:

$('#search').keypress(function (evt) {
    // the AJAX part
    var flickerAPI = "http://api.flickr.com/services/feeds/photos_public.gne?jsoncallback=?";
    var animal = $(this).val();;
    var flickrOptions = {
      tags: animal,
      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>';
    $.getJSON(flickerAPI, flickrOptions, displayPhotos);

however, when I enter "cat" for example I get results for what I think is "catch" instead. I know we were told that you have no control on the order that the AJAX requests are coming back. But there must be a way right? I've seen this live search functionality on other sites...


2 Answers

Vitaliy Bogdanov
Vitaliy Bogdanov
7,612 Points

Function is ok. But there is one weak spot. The fact that the event "keypress" triggered earlier than changing the value of the input field. Therefore, the first time function send empty request, then the letter "c", and then "ca". It is easy to check to add console.log ($ (this) .val ()); in function start.

My solution is to change the event handler in the "keyup"

Or make use of the delay through setTimeout() and wait for the end of the input.

Daniel Zlatanov
Daniel Zlatanov
3,695 Points

I have tried with .keyup() as suggested by Vitaliy and it works great!