Single Image from Flikr using API in AJAX
Here is a code example of how to get one single image out of Flikr, and place it into a html page using AJAX.
Just call getImageFromFlikr with the search text, and an output element. It works asynchronously, so it will return as soon as Flikr is contacted.
function getImageFromFlikr(searchText, output)
{
try
{
xmlhttp=new XMLHttpRequest();
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState!=4) return;
if (xmlhttp.status != 200)
{
output.innerHTML = “Error”;
}
if (xmlhttp.status == 200)
{
output.innerHTML = eval(xmlhttp.responseText); //retrieve result as an JavaScript object
}
}
var strUrl = “http://api.flickr.com/services/rest/?”;
strUrl += “method=flickr.photos.search”;
strUrl += “&api_key=cabbc1b68c18461ca0627991833d8f97”;
strUrl += “&text=” + encodeURIComponent(searchText);
strUrl += “&per_page=1”;
strUrl += “&format=json”;
strUrl += “&sort=relevance”;
xmlhttp.open(“GET”,strUrl,true);
xmlhttp.open(“GET”,strUrl,true);
xmlhttp.send();
}
catch (err)
{
output.innerHTML = err.message;
}
}function jsonFlickrApi(flikrObj)
{
var fmt=”http://farm{farm-id}.static.flickr.com/{server-id}/{id}_{secret}_m.jpg”;
fmt = fmt.replace(“{farm-id}”,flikrObj.photos.photo[0].farm);
fmt = fmt.replace(“{server-id}”,flikrObj.photos.photo[0].server);
fmt = fmt.replace(“{id}”,flikrObj.photos.photo[0].id);
fmt = fmt.replace(“{secret}”,flikrObj.photos.photo[0].secret);
var html = “<img src='” + fmt + “‘>”;
return html;
}