jQuery tip: Reading JSONP from an external server

This tip is extracted from the book, jQuery, jQuery UI, and jQuery Mobile: Recipes and Examples by Phillip Dutson and Adriaan de Jonge, published by Pearson/Addison-Wesley Professional, Nov 2012, ISBN 9780321822086. For more info, please visit the publisher site. Related video training includes: "jQuery Fundamentals LiveLessons (Video Training)"

[ Enter ITworld's drawing to win a copy of jQuery, jQuery UI, and jQuery Mobile: Recipes and Examples ]

Classic AJAX works with the XmlHttpRequest (XHR) object. Most browsers do not allow XHR to access other servers than the origin of the current page. To work around this limitation, JSONP was invented.

JSONP is JSON wrapped inside a function call. Instead of making an AJAX request, a script element pointing to the JSONP script is added inside the HTML document and a callback function is called to access the script.


The browser vendors who restricted the use of XHR had good reason to do so: security. Working around these restrictions with JSONP opens up new possibilities for hackers because JSONP does not allow validation before execution.

Listing 5.13 demonstrates how to retrieve data from Twitter by using JSONP. Keep in mind that error handling does not work with JSONP.

Listing 5.13: Connecting to Twitter and Searching for jQuery-Related Posts

00 <!DOCTYPE html>


02 <html lang="en">

03 <head>

04   <title>Get JSONP</title>

05 </head>

06 <body>


08 <h2>Press the button to perform the request.</h2>


10 <button id="trigger">GET</button>

11 <br>

12 <div id="target">



15 <script src="http://code.jquery.com/jquery-1.7.2.min.js"></script>


17 <script>

18 // please externalize this code to an external .js file

19 $(document).ready(function() {


21   $('#trigger').click(function() {


23     $.getJSON('http://search.twitter.com/search.json' +

24         '?q=jquery&callback=?', function(data) { 


26       $.each(data.results, function(index, value) {


28         $('#target').append(value.text + '<br>');


30       });


32     });


34   });


36 });

37 </script>

38 </body>

39 </html>

By default, the JSONP handler in jQuery looks for a callback=? parameter in the query string. The ? is replaced with a jQuery-generated callback function to be inserted into JSONP by the server.

You can modify settings if the parameter has another name than callback or when the callback method is not parameterized. If you insist, you can find these parameters in the jQuery online documentation.

The best advice is to avoid JSONP whenever possible.

ITWorld DealPost: The best in tech deals and discounts.
Shop Tech Products at Amazon