{"id":255,"date":"2011-01-19T16:41:54","date_gmt":"2011-01-19T16:41:54","guid":{"rendered":"http:\/\/www.osd.net\/blog\/?p=255"},"modified":"2013-05-10T15:25:52","modified_gmt":"2013-05-10T15:25:52","slug":"jsonp-example","status":"publish","type":"post","link":"https:\/\/www.osd.net\/blog\/web-development\/javascript\/jsonp-example\/","title":{"rendered":"JSONP Example"},"content":{"rendered":"<p><strong>JSONP <\/strong>is the answer to two quite popular questions among the web developers:<\/p>\n<ul>\n<li>how can I make an <strong>asynchronous <\/strong>call to an script that is not on my server?<\/li>\n<li>how can I &#8220;hide&#8221; my <strong>ajax <\/strong>calls in the javascript console?<\/li>\n<\/ul>\n<h1>What is JSONP?<\/h1>\n<p>Short version: it&#8217;s an <strong>alternative to ajax<\/strong>.<\/p>\n<p>Long version(with example) below:<\/p>\n<p>I guess most of you know what is JSON. If you don&#8217;t there is a lot of information out there about it. You could start by reading some of the wikipedia article on <a title=\"Wikipedia - JSON\" href=\"http:\/\/en.wikipedia.org\/wiki\/JSON\" target=\"_blank\">json<\/a> (you will also find some things about jsonp in that article).<\/p>\n<p>JSONP is nothing else but <strong>json with padding<\/strong>. This technology is based on a very simple principle: the fact that you can dynamically add new external javascript sources in your website without problem and that a json response is easy to handle with javascript.<\/p>\n<p>So back to the two questions: notice that the first one uses the term &#8220;asynchronous&#8221; but not the well known &#8220;ajax&#8221;. That is because <strong>jsonp<\/strong> calls are not in fact ajax calls. This thing answers the second question also: the calls that you know that are made but you don&#8217;t see them in the javascript console are not ajax calls.<\/p>\n<p>What do you need to do in order to make a jsonp call?<\/p>\n<p>When you need to make the call dynamically insert into your page a new &lt;script&gt; tag. The source should be a service that outputs a json.<\/p>\n<p>What&#8217;s the padding? If you just output a json encoded object in your script at the moment you insert it in your page you will have a new object, but nothing will happen with it. So you can add a function that you know it is available in the page that can &#8220;read&#8221; the output.<\/p>\n<h1>Full working example:<\/h1>\n<p><strong>HTML\/JS<\/strong>:<\/p>\n<pre class=\"brush: jscript; title: ; notranslate\" title=\"\">\r\n\r\n&lt;script type=&quot;text\/javascript&quot;&gt;\/\/ &lt;![CDATA[\r\n\t\t\tfunction callTheJsonp()\r\n\t\t\t{\r\n\t\t\t\t\/\/ the url of the script where we send the asynchronous call\r\n\t\t\t\tvar url = &quot;http:\/\/localhost\/utils\/jsonp\/ajax.php?callback=parseRequest&quot;;\r\n\t\t\t\t\/\/ create a new script element\r\n\t\t\t\tvar script = document.createElement('script');\r\n\t\t\t\t\/\/ set the src attribute to that url\r\n\t\t\t\tscript.setAttribute('src', url);\r\n\t\t\t\t\/\/ insert the script in out page\r\n\t\t\t\tdocument.getElementsByTagName('head')[0].appendChild(script);\r\n\t\t\t}\r\n\r\n\t\t\t\/\/ this function should parse responses.. you can do anything you need..\r\n\t\t\t\/\/ you can make it general so it would parse all the responses the page receives based on a response field\r\n\t\t\tfunction parseRequest(response)\r\n\t\t\t{\r\n\t\t\t\ttry \/\/ try to output this to the javascript console\r\n\t\t\t\t{\r\n\t\t\t\t\tconsole.log(response);\r\n\t\t\t\t}\r\n\t\t\t\tcatch(an_exception) \/\/ alert for the users that don't have a javascript console\r\n\t\t\t\t{\r\n\t\t\t\t\talert('product id ' + response.item_id + ': quantity = ' + response.quantity + ' &amp; price = ' + response.price);\r\n\t\t\t\t}\r\n\t\t\t}\r\n\r\n\/\/ ]]&gt;&lt;\/script&gt;\r\n\r\n &lt;span onclick=&quot;callTheJsonp()&quot;&gt;click here to make the jsonp call&lt;\/span&gt;\r\n\r\n<\/pre>\n<p><strong>PHP<\/strong>:<\/p>\n<pre class=\"brush: php; title: ; notranslate\" title=\"\">\r\n&lt;?php\r\n\t\/\/ get the callback function name\r\n\t$callback = '';\r\n\tif (isset($_GET['callback']))\r\n\t{\r\n\t\t$callback = filter_var($_GET['callback'], FILTER_SANITIZE_STRING);\r\n\t}\r\n\r\n\t\/\/ make an array with some random values.. so you would see that the results are fetched each time you call this script\r\n\t$array = array(\r\n\t\t\t\t\t'item_id' =&gt; rand(1,13),\r\n\t\t\t\t\t'price' =&gt; rand(14,17),\r\n\t\t\t\t\t'quantity' =&gt; rand(18,30)\r\n\r\n\t);\r\n\t\/\/ output this array json encoded.. the callback function being the padding (a function available in the web page)\r\n\techo $callback . '('.json_encode($array).');';\r\n<\/pre>\n<p>What just happened?<\/p>\n<p>When the user clicks on the span the <strong>callTheJsonp<\/strong> function is called. This function will insert into the page a new element and its source will be in fact a <strong>php script<\/strong>. (keep in mind: even if I called that file ajax.php, this is not an ajax)<\/p>\n<p>The php will output his response between <strong>parseRequest(<\/strong> and <strong>)<\/strong>. So when the response arrives the <strong>parseRequest function<\/strong> will be called and the parameter will be the result of the script we called.<\/p>\n<p>So now inside the parseRequest function you have an <strong>javascript object<\/strong> with everything you need. From here on you can do anything you want, just the way you did with ajax.<\/p>\n<p>Downsides? A few: <strong>ajax is safer<\/strong> (that&#8217;s why you can&#8217;t make ajax calls to external servers) so you must take care what you do with the response or the fact that you <strong>can&#8217;t use POST<\/strong> as a request method.<\/p>\n<p>You can download a full working example <a title=\"Full working jsonp example\" href=\"https:\/\/www.osd.net\/blog\/wp-content\/uploads\/2011\/01\/jsonp.zip\">here<\/a>.<\/p>\n<p>If you have any questions or feedback please feel free to use the form below to add a comment.<\/p>\n<div id=\"share-and-beer-container\">\t<div id=\"buy_me_a_beer_div\" class=\"single beer\">\n\t \t\n\t\t<div class=\"buy-beer\" onclick=\"document.getElementById('buy_me_a_beer_form').submit();\">\n\t\t\t<form action=\"https:\/\/www.paypal.com\/cgi-bin\/webscr\" id=\"buy_me_a_beer_form\" method=\"post\">\n\t\t\t\t<input type=\"hidden\" name=\"cmd\" value=\"_xclick\" \/>\n\t\t\t\t<input type=\"hidden\" name=\"business\" value=\"info@directaccess.ro\" \/>  \n\t\t\t\t<input type=\"hidden\" name=\"item_name\" value=\"A Beer For JSONP Example\" \/>  \n\t\t\t\t<input type=\"hidden\" name=\"item_number\" value=\"1\" \/>  \n\t\t\t\t<input type=\"hidden\" name=\"return\" value=\"https:\/\/www.osd.net\/blog\/web-development\/javascript\/jsonp-example\/\" \/>  \n\t\t\t\t<input type=\"hidden\" name=\"amount\" value=\"5\" \/>  \n\t\t\t\t<input type=\"hidden\" name=\"undefined_quantity\" value=\"1\" \/>  \n\t\t\t\t<input type=\"hidden\" name=\"currency_code\" value=\"USD\" \/>  \n\t\t\t<\/form>\n\t\t\t<p class=\"buy-beer-text\">If you liked this post <br \/> you can <strong>buy me a beer<\/strong><\/p>\n\t\t<\/div>\n\t<\/div><\/div>","protected":false},"excerpt":{"rendered":"<p>JSONP is the answer to two quite popular questions among the web developers: how can I make an asynchronous call to an script that is not on my server? how can I &#8220;hide&#8221; my ajax calls in the javascript console? What is JSONP? Short version: it&#8217;s an alternative to ajax. Long version(with example) below: I &hellip;<\/p>\n<div class=\"cta1\"><a href=\"https:\/\/www.osd.net\/blog\/web-development\/javascript\/jsonp-example\/\">Read more<\/a><\/div>\n<div class=\"like-excerpt\"><div\n        class=\"fb-like\"\n        data-href=\"https:\/\/www.osd.net\/blog\/web-development\/javascript\/jsonp-example\/\"\n        data-layout=\"button_count\"\n        data-action=\"like\"\n        data-show-faces=\"false\"\n        data-share=\"false\">\n        <\/div><\/div>","protected":false},"author":2,"featured_media":0,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":[],"categories":[18],"tags":[57,55,63,64,35],"_links":{"self":[{"href":"https:\/\/www.osd.net\/blog\/wp-json\/wp\/v2\/posts\/255"}],"collection":[{"href":"https:\/\/www.osd.net\/blog\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/www.osd.net\/blog\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/www.osd.net\/blog\/wp-json\/wp\/v2\/users\/2"}],"replies":[{"embeddable":true,"href":"https:\/\/www.osd.net\/blog\/wp-json\/wp\/v2\/comments?post=255"}],"version-history":[{"count":11,"href":"https:\/\/www.osd.net\/blog\/wp-json\/wp\/v2\/posts\/255\/revisions"}],"predecessor-version":[{"id":261,"href":"https:\/\/www.osd.net\/blog\/wp-json\/wp\/v2\/posts\/255\/revisions\/261"}],"wp:attachment":[{"href":"https:\/\/www.osd.net\/blog\/wp-json\/wp\/v2\/media?parent=255"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/www.osd.net\/blog\/wp-json\/wp\/v2\/categories?post=255"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/www.osd.net\/blog\/wp-json\/wp\/v2\/tags?post=255"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}