Parsing the Response
The results that are returned as the response are accessible via the request object. In order to access the results, we need to access the request’s responseText property and then parse it into a valid JSON string that we can work with. With the jsonparser included, this is very simple: All we do to parse the response as JSON is:
var gimages = this.request.responseText.parseJSON();
Once we’ve parsed the response, we need to get to the results, which are always included in a responseData object that includes an array named results (see Table 4). Iterating the results array allows us to access the properties of each image result and create an HTML structure to render the images on the web page.
var results = gimages.responseData.results;
Table 4Google Image Search Properties
Property |
Description |
title |
Title of the image |
titleNoFormatting |
Title of the image with no HTML |
unescapedUrl |
Raw URL of image |
url |
Escaped URL of image |
visibleUrl |
Short URL associated with result |
originalContextUrl |
URL of the original source page for the image |
width |
Width of image in pixels |
height |
Height of image in pixels |
tbWidth |
Width of image thumbnail in pixels |
tbHeight |
Height of image thumbnail in pixels |
tbUrl |
URL of thumbnail image |
content |
Snippet of information from the image’s original source page |
contentNoFormatting |
Same snippet of information as content, with no HTML |
In the example, we’re accessing each individual image result’s URL property for the escaped version of the image URL, which we’ll use to create an image element to be rendered on the web page as HTML.
Next, we create an anchor element to wrap the image and set the href to the image’s originalContextUrl, which links all the images to their original source. Once the image has been created with the anchor tag, we can add it to the div in the HTML with an id of gimages. To add a little interactivity to the widget, we’ll create a simple auto-refresh function to update the widget automatically. Simply set an interval in the window.onload function that calls the GoogleAPI.SearchImages method every 10 seconds.
Listing 2The GoogleAPI object makes Ajax requests, parses results and renders the widget as HTML (GoogleAPI.js)
document.write('<script type="text/javascript" src="assets/js/jsonparser.js"></script>'); var GoogleAPI = new Object(); GoogleAPI.imageQuery = "Peachpit"; GoogleAPI.SearchImages = function() { GoogleAPI.callback = GoogleAPI.onImagesSearched; var gateway = "service/gateway.php?feed="+ escape("http://ajax.googleapis.com/ajax/ services/search/images?v=1.0&rsz=small&start="+ Math.floor((Math.random()*50)+1) +"&q=")+ GoogleAPI.imageQuery; GoogleAPI.makeRequest(gateway); } GoogleAPI.onImagesSearched = function(request) { var divImages = document.getElementById('gimages'); divImages.innerHTML = ''; if(this.request.responseText) { var gimages = this.request.responseText.parseJSON(); var results = gimages.responseData.results; if(results.length > 0) { for(var i=0; i<results.length; i++) { var image = document.createElement('img'); image.src = results[i].url.replace(/%2520/g, "%20"); var imageAnchor = document.createElement('a'); imageAnchor.target = '_blank'; imageAnchor.href = results[i].originalContextUrl; imageAnchor.className = 'gimageAnchor'; imageAnchor.appendChild(image); divImages.appendChild(imageAnchor); } } else GoogleAPI.ThrowError("There were no image results"); } else GoogleAPI.ThrowError("There was an error receiving the images feed"); } GoogleAPI.makeRequest = function(gw) { this.request = (window.XMLHttpRequest) ? new XMLHttpRequest(): new ActiveXObject("Microsoft.XMLHTTP"); this.request.onreadystatechange = function() { GoogleAPI.checkReadyState(); }; this.request.open('GET', gw, true); this.request.send(gw); } GoogleAPI.ThrowError = function(msg) { alert(msg); } GoogleAPI.checkReadyState = function() { switch(this.request.readyState) { case 1: break; case 2: break; case 3: break; case 4: this.callback(this.request); } } window.onload = function() { GoogleAPI.SearchImages(); __imgInterval = setInterval(GoogleAPI.SearchImages, 10000); }