Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

JavaScript

ilham salahov
ilham salahov
11,273 Points

Problem with AJAX API

I want the program to say "We couldn't find it" when the searched item is not found, but, it doesn't work. What am i doing wrong? Please help.

$(document).ready(function() {

$('form').submit(function (evt) { // highlight the button // not AJAX, just cool looking // the AJAX part var $searchField = $('#search'); var $submitButton = $('#submit'); $searchField.prop('disabled', true); $submitButton.attr('disabled', true).val('searching......'); evt.preventDefault(); var flickerAPI = "http://api.flickr.com/services/feeds/photos_public.gne?jsoncallback=?"; var input = $('#search').val(); var flickrOptions = { tags: input, format: "json" }; $.getJSON(flickerAPI, flickrOptions, displayPhotos);

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>';
  if(photoHTML == null) {
     $('#photos').html("We couldn't find it");
} else {
    $('#photos').html(photoHTML); 
}
  $searchField.prop('disabled', false);
  $submitButton.attr('disabled', false).val('Search');

}

$.getJSON(flickerAPI, flickrOptions, displayPhotos);

}); // end click }); // end ready

1 Answer

Cheo R
Cheo R
37,150 Points

Is it never dropping into the line "We couldn't find it" ?

If so, quick glance, the problem seems to lie with:

  var photoHTML = '<ul>';
        ...
  photoHTML += '</ul>';
  if(photoHTML == null)

The variable photoHTML is never null because before/after your ajax call, you already assign it to something (in these cases, strings.

ilham salahov
ilham salahov
11,273 Points

I have tried ways too. Like: if(data.items === []). But it just won't work. i know for sure that the problem lies in the if statement, but, i cannot find the right solution.