Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Basic example of using .ajax() with JSONP?

Tags:

json

ajax

jsonp

Please could someone help me work out how to get started with JSONP?

Code:

$('document').ready(function() {     var pm_url = 'http://twitter.com/status';     pm_url += '/user_timeline/stephenfry.json';     pm_url += '?count=10&callback=photos';     var photos = function (data) {      alert(data);     };     $.ajax({         url: pm_url,         dataType: 'jsonp',         jsonpCallback: 'photos',         jsonp: false,     }); }); 

Fiddle: http://jsfiddle.net/R7EPt/6/

Should produce an alert, as far as I can work out from the documentation: isn't (but isn't producing any errors either).

thanks.

like image 306
simon Avatar asked May 09 '11 23:05

simon


People also ask

Can JSONP be used with AJAX?

JSONP allows you to sidestep the same-origin policy and to some extent make cross-domain Ajax calls. It's not a silver bullet, and it certainly has its issues, but in some cases it can prove invaluable when fetching data from a different origin.

What is JSONP in AJAX?

JSONP stands for JSON with Padding. Requesting a file from another domain can cause problems, due to cross-domain policy. Requesting an external script from another domain does not have this problem. JSONP uses this advantage, and request files using the script tag instead of the XMLHttpRequest object.

What is AJAX explain with example?

AJAX allows web pages to be updated asynchronously by exchanging small amounts of data with the server behind the scenes. This means that it is possible to update parts of a web page, without reloading the whole page. Classic web pages, (which do not use AJAX) must reload the entire page if the content should change.

What is dataType JSONP?

dataType: jsonp for cross-domain request, that means request to different domain and dataType: json for same domain-same origin request. Loads in a JSON block using JSONP. Adds an extra "? callback=?" to the end of your URL to specify the callback.


2 Answers

JSONP is really a simply trick to overcome XMLHttpRequest same domain policy. (As you know one cannot send AJAX (XMLHttpRequest) request to a different domain.)

So - instead of using XMLHttpRequest we have to use script HTMLl tags, the ones you usually use to load JS files, in order for JS to get data from another domain. Sounds weird?

Thing is - turns out script tags can be used in a fashion similar to XMLHttpRequest! Check this out:

script = document.createElement("script"); script.type = "text/javascript"; script.src = "http://www.someWebApiServer.com/some-data"; 

You will end up with a script segment that looks like this after it loads the data:

<script> {['some string 1', 'some data', 'whatever data']} </script> 

However this is a bit inconvenient, because we have to fetch this array from script tag. So JSONP creators decided that this will work better (and it is):

script = document.createElement("script"); script.type = "text/javascript"; script.src = "http://www.someWebApiServer.com/some-data?callback=my_callback"; 

Notice my_callback function over there? So - when JSONP server receives your request and finds callback parameter - instead of returning plain JS array it'll return this:

my_callback({['some string 1', 'some data', 'whatever data']}); 

See where the profit is: now we get automatic callback (my_callback) that'll be triggered once we get the data. That's all there is to know about JSONP: it's a callback and script tags.


NOTE:
These are simple examples of JSONP usage, these are not production ready scripts.

RAW JavaScript demonstration (simple Twitter feed using JSONP):

<html>     <head>     </head>     <body>         <div id = 'twitterFeed'></div>         <script>         function myCallback(dataWeGotViaJsonp){             var text = '';             var len = dataWeGotViaJsonp.length;             for(var i=0;i<len;i++){                 twitterEntry = dataWeGotViaJsonp[i];                 text += '<p><img src = "' + twitterEntry.user.profile_image_url_https +'"/>' + twitterEntry['text'] + '</p>'             }             document.getElementById('twitterFeed').innerHTML = text;         }         </script>         <script type="text/javascript" src="http://twitter.com/status/user_timeline/padraicb.json?count=10&callback=myCallback"></script>     </body> </html> 


Basic jQuery example (simple Twitter feed using JSONP):

<html>     <head>         <script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.6.2/jquery.min.js"></script>         <script>             $(document).ready(function(){                 $.ajax({                     url: 'http://twitter.com/status/user_timeline/padraicb.json?count=10',                     dataType: 'jsonp',                     success: function(dataWeGotViaJsonp){                         var text = '';                         var len = dataWeGotViaJsonp.length;                         for(var i=0;i<len;i++){                             twitterEntry = dataWeGotViaJsonp[i];                             text += '<p><img src = "' + twitterEntry.user.profile_image_url_https +'"/>' + twitterEntry['text'] + '</p>'                         }                         $('#twitterFeed').html(text);                     }                 });             })         </script>     </head>     <body>         <div id = 'twitterFeed'></div>     </body> </html> 


JSONP stands for JSON with Padding. (very poorly named technique as it really has nothing to do with what most people would think of as “padding”.)

like image 181
ThatGuy Avatar answered Nov 27 '22 09:11

ThatGuy


There is even easier way how to work with JSONP using jQuery

$.getJSON("http://example.com/something.json?callback=?", function(result){    //response data are now in the result variable    alert(result); }); 

The ? on the end of the URL tells jQuery that it is a JSONP request instead of JSON. jQuery registers and calls the callback function automatically.

For more detail refer to the jQuery.getJSON documentation.

like image 38
Petr Peller Avatar answered Nov 27 '22 09:11

Petr Peller