Search code examples
jqueryflickr

create img link from flickr api response


I need get first image from flickr by title and from response create link. But I cannot find photo element and I don't know why. My code:

var options = { 
  "api_key": API-KEY,
  "method": "flickr.photos.search",
  "accuracy": "11",
  "content_type": "1",
  "format": "xmlrpc",
  "per_page": "1",
  "text": TITLE
}

var makeFlickrRequest = function(options, cb) {
    var url, item, first;

    url = "http://api.flickr.com/services/rest/";
    first = true;
    $.each(options, function(key, value) { 
        url += (first ? "?" : "&") + key + "=" + value;
        first = false; 
    });

    $.get(url, function(data) {
        $(data).find('photo').each(function(){
            cb($(this));
        });
    });
};

Only thing I can get is text from string element when I change code to

$(data).find('string').each(function(){
    cb($(this).text());
});

but I want rather work with element attributes like parsing text like:

<photos page="1" pages="222177" perpage="1" total="222177">
    <photo id="9494235388" owner="16159287@N02" secret="f5dbd3b43a" server="7443"    farm="8" title="2013 River Cruise Day 13 Bratislava" ispublic="1" isfriend="0" isfamily="0" />
</photos>

Api response:

<methodResponse><params><param><value><string>
    <photos page="1" pages="222189" perpage="1" total="222189">
        <photo id="9494235388" owner="16159287@N02" secret="f5dbd3b43a" server="7443" farm="8" title="2013 River Cruise Day 13 Bratislava" ispublic="1" isfriend="0" isfamily="0" />
    </photos>
</string></value></param></params></methodResponse>

Solution

  • afaik you can change the format option to "json"

    var options = { 
      "api_key": API-KEY,
      "method": "flickr.photos.search",
      "accuracy": "11",
      "content_type": "1",
      "format": "json",                    //<--- JSON format
      "per_page": "1",
      "text": TITLE
    }
    

    that way it'll be easier to parse the response, i think...

    $.get(url, function(data) {
        $.each(data.photos, function(){
            console.log(this);  //<-- your photo object
        });
    });