jQuery and JSON-P

Utilize jQuery and JSON-P to create a AJAX-driven search tool with Google’s AJAX Search API. Click Here for a Demo!

In an effort to help me learn how cross domain requests work, and in order to do something a little cool, I’ve developed a very simple search-as-you-type script which leverages Google’s AJAX Search API and outputs the results within the body of the page.

Cross Domain Requests with JSON-P

One of the hurdles to overcome with a lot of AJAX-enabled web applications is the ability to get information and content from outside sources. This is limited in the fact that most browsers attempt to “sandbox” this DOM access through something called the same-origin policy. In order to circumvent the same-origin policy, a method commonly employed is to utilize something called JSON-P.

The key to this example is the ability to send a request to Google’s AJAX Search API and receive meaningful (and structured) results. This is fairly easily handled using JSON-P. JSON (JavaScript Object Notation) is a lightweight data interchange format, typically used to pass information as JavaScript data structures via AJAX.

Example JSON string:

{
	"responseData":{
		"results":[{
			"GsearchResultClass":"GwebSearch",
			"unescapedUrl":"http://en.wikipedia.org/wiki/Budgie",
			"url":"http://en.wikipedia.org/wiki/Budgie",
			"visibleUrl":"en.wikipedia.org",
			"cacheUrl":"http://www.google.com/search?q\u003dcache:r3jDD45mJXUJ:en.wikipedia.org",
			"title":"\u003cb\u003eBudgie\u003c/b\u003e - Wikipedia, the free encyclopedia",
			"titleNoFormatting":"Budgie - Wikipedia, the free encyclopedia",
			"content":"\u003cb\u003eBudgie\u003c/b\u003e has several meanings: Budgerigar, a type of bird; \u003cb\u003eBudgie\u003c/b\u003e (band), a rock   band. \u003cb\u003eBudgie\u003c/b\u003e (album), the self-titled debut album of the above band \u003cb\u003e...\u003c/b\u003e"
		}]
	},
	"responseDetails": null,
	"responseStatus": 200
}

A JSON-P request, or “JSON with padding,” is a JSON string that is surrounded by a function call which is invoked when the request is received by the browser. In order to make use of the Google AJAX Search API and make it output its JSON-P code correctly, a parameter called callback is sent with the rest of the request so that the API can return a formatted string. Calling the Google AJAX Search API with a request such as http://ajax.googleapis.com/ajax/services/search/web?callback=processResponse&v=1.0&q=budgie&rsz=large will be formatted like:

processResponse({
	"responseData":{
		"results":[{
			"GsearchResultClass":"GwebSearch",
			"unescapedUrl":"http://en.wikipedia.org/wiki/Budgie",
			"url":"http://en.wikipedia.org/wiki/Budgie",
			"visibleUrl":"en.wikipedia.org",
			"cacheUrl":"http://www.google.com/search?q\u003dcache:r3jDD45mJXUJ:en.wikipedia.org",
			"title":"\u003cb\u003eBudgie\u003c/b\u003e - Wikipedia, the free encyclopedia",
			"titleNoFormatting":"Budgie - Wikipedia, the free encyclopedia",
			"content":"\u003cb\u003eBudgie\u003c/b\u003e has several meanings: Budgerigar, a type of bird; \u003cb\u003eBudgie\u003c/b\u003e (band), a rock   band. \u003cb\u003eBudgie\u003c/b\u003e (album), the self-titled debut album of the above band \u003cb\u003e...\u003c/b\u003e"
		}]
	},
	"responseDetails": null,
	"responseStatus": 200
})

Note the difference in the JSON-P code versus the JSON code. The JSON-P code is wrapped with the callback function so that when the request is returned to the browser, it gets invoked and the JSON content can be processed in some fashion.

JSON-P gets around the same-origin policy by treating JSON as a JavaScript function rather than pure GET requests.

Bob Ippolito’s article on Remote JSON
Google AJAX Search API
Google’s Browser Security Handbook

Using jQuery to Handle JSON-P Requests

Since jQuery 1.2, JSON-P has been supported natively. This means that you can simply use jQuery’s built-in AJAX functions like you would with any regular AJAX request and the jQuery framework will handle the creation of the callback methods for you.

There are two simple ways to leverage jQuery’s functionality. The first is to utilize the $.getJSON method, but append callback=? to the URL. By providing this extra piece to the URL, jQuery knows to generate a function name based on the function provided in the 2nd argument:

$.getJSON('http://ajax.googleapis.com/ajax/services/search/web?v=1.0&q=budgie&rsz=large&callback=?', function(data) {
	// do something with data returned
});

The script shown above generates a URL string like http://ajax.googleapis.com/ajax/services/search/web?v=1.0&q=test&rsz=large&callback=jsonp1265566314033. The created callback name refers to the anonymous function provided to the $.getJSON method.

The other approach is to use jQuery’s $.ajax method. Rather than passing in callback=? with the URL string, you can simply set the dataType option to be jsonp. jQuery will then handle the rest for you. Below is an excerpt of code that is used in the demo.

function doSearch(searchQuery) {
	// perform our ajax request
	$.ajax({
		url: 'http://ajax.googleapis.com/ajax/services/search/web',
		data: {
			v: '1.0',
			q: searchQuery,
			rsz: 'large'
		},
		dataType: 'jsonp',
		type: 'GET',
		success: function(data) {
			// do some stuff with the returned data
		}
	});
}

Conclusion

As you can see, jQuery provides some very powerful methods to achieve some cross-domain communication without resorting to a server-side proxy. JSON-P is definitely a useful way to send and receive information and to get around the restrictions imposed by the browsers.

Tags: , , , , , ,

Leave a Reply