ClaytonAlanKinder
ClaytonAlanKinder

Reputation: 335

Why does the Flickr public feed API return "undefined" before displaying photo results when accessed by jQuery?

I started working with APIs/Ajax/JSON recently and began a small project to test my knowledge.

I made a simply website where you type a word into a form and it brings back Flickr photos associated with the word.

It works pretty well, but it always includes a simple "undefined" before the first photo which messes with the display of the first row of pictures.

An example can be seen here, simply search for a photo tag and you'll see what I'm talking about:

http://codepen.io/anon/pen/jPExNm

Here is the related jQuery:

$('form').submit(function (evt) {
evt.preventDefault();
// the AJAX part
var flickerAPI = "http://api.flickr.com/services/feeds/photos_public.gne?jsoncallback=?";
var query = $('#photoQuery').val();
var flickrOptions = {
  tags: query,
  format: "json"
};
function displayPhotos(data) {
  var photoHTML;
  $.each(data.items,function(i,photo) {
    photoHTML += '<div class="photo">';
    photoHTML += '<a href="' + photo.link + '" class="image">';
    photoHTML += '<img src="' + photo.media.m + '"></a></div>';
  }); // end each
  $('#photoGallery').html(photoHTML);
}
$.getJSON(flickerAPI, flickrOptions, displayPhotos);

}); // end submit

I haven't found any errors related to this in the Javascript console and couldn't find anything like this while Googling, so I'm turning to StackOverflow. Thank you for any and all help.

Upvotes: 1

Views: 281

Answers (1)

epascarello
epascarello

Reputation: 207511

Because

var photoHTML;

is the same thing as

var photoHTML = undefined;

Basic example of what you are doing

var str;
str = str + "123"; // undefined + "123" = "undefined123";

You need to set it to an empty string

var photoHTML = "";

Upvotes: 2

Related Questions