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>';
      $('#photos').html(photoHTML); 
    }
    $.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...

Thanks!

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!