{"id":81,"date":"2009-06-21T21:48:29","date_gmt":"2009-06-21T21:48:29","guid":{"rendered":"http:\/\/localhost\/tfcom_wp\/2009\/06\/21\/jquery-jsonp\/"},"modified":"2009-06-21T21:48:29","modified_gmt":"2009-06-21T21:48:29","slug":"jquery-jsonp","status":"publish","type":"post","link":"https:\/\/www.tech-freaks.com\/java\/javascript\/jquery-jsonp.html","title":{"rendered":"Using Jquery with JSONP"},"content":{"rendered":"<p style=\"text-align: left;\"><strong>The workshop is for<\/strong><\/p>\n<p style=\"text-align: left;\">This workshop is dedicated to all those who are stuck with cross-domain communication issue trying to fetch JSON data from a different domain using Jquery.<\/p>\n<p><strong>Introduction<\/strong><\/p>\n<p style=\"text-align: left;\">This workshop is built up based on &#8216;JSON with Jquery&#8217; workshop. It starts by providing a working example of JSON service accessed by Jquery and highlights cross-domain communication issue while trying to access JSON data from a different domain. It then goes on showing the resolution using JSONP (JSON with Padding).<\/p>\n<p><strong>Quick Recap<\/strong><\/p>\n<p style=\"text-align: left;\">Let us have a quick recap of the example &#8216;JSON with Jquery&#8217;. However, it is strongly recommended to have go through\u00a0<a title=\"Using Jquery with JSON\" href=\"Java-Programming\/Javascripts\/jquery-json.html\" target=\"_blank\" rel=\"noopener noreferrer\">JSON with Jquery\u00a0<\/a>workshop just to get an idea of what the example deals with. Here is a summary:<\/p>\n<ol style=\"text-align: left;\">\n<li>A\u00a0HTML page has the Jquery code to access JSON and generate dynamic dropdowns.<\/li>\n<li>There are two predefined static JSON files one for category and another for articles.<\/li>\n<\/ol>\n<p style=\"text-align: left;\"><strong>Dynamically generated JSON files<\/strong><\/p>\n<p>We will be modifying the previous workshop example to generate dynamic JSON files using server side components (like JSP\/Servlet, PHP etc). So, we will create a JSP\/PHP which spits out a JSON data. We create a PHP file by the name getSiteJSON.php. Here, we merge the content of two static JSON files used previously into a single server component. Note that our JSON file is still static, as the contents are hardcoded. However, in real life your JSON contents will be dynamically pulled from\u00a0the database.<\/p>\n<p>The below code snippet highlights the change in the Jquery JSON call in the html file.<\/p>\n<pre class=\"language-javascript\"><code>$.getJSON(\"http:\/\/www.stage3.tech-freaks.in\/sourcecode\/jquery_jsonp\/\r\n                      getSiteJson.php?type=category\",  function(json) {\r\n          var catJson = json[sSec];\r\n          var options = \"&lt;option value=\\\"select\\\"&gt;Select&lt;\/option&gt;\";\r\n          for(i=0;i&lt;catJson.length;i++) {<\/code><\/pre>\n<p>The below code snippets is a PHP code which generates JSON.<\/p>\n<pre class=\"language-php\"><code>   $type = $_GET['type'];\r\n    $jsonData = \"\";\r\n    if($type==\"category\")\r\n        $jsonData = \"{\\\"java_programming\\\": [ { \\\"ky\\\": \\\"java_basics\\\", ....}]}\";\r\n    else\r\n        $jsonData = \"{\\\"java_basics\\\": [\\\"Java Hello World - Tech Programmer\\\", ...]}\";\r\n    echo $jsonData;<\/code><\/pre>\n<p style=\"text-align: left;\">\u00a0You may want to check the working of the getSiteJSON.php by accessing the page directly with query parameter of &#8216;type=category&#8217; or &#8216;type=article&#8217; and see the JSON printed in the page.<\/p>\n<p><strong>Cross domain JSON fetch<\/strong><\/p>\n<p style=\"text-align: left;\">Now, let us assume that we want to get the site data as JSON from a different site. From a technical perspective, this means that getSiteJSON.php or some service similar to it is present in a different domain. This is common with JSON services provided by a different site and used by another site.\u00a0<\/p>\n<p>For this workshop, we simulate this\u00a0scenario by hosting the getSiteJSON.php in\u00a0<em>www.stage3.tech-freaks.in<\/em>\u00a0and the HTML page which fetches the JSON content using Jquery in\u00a0<em>www.tech-freaks.in<\/em>.<\/p>\n<p>Uploading files&#8230;..<\/p>\n<p>Check\u00a0<a title=\"Cross domain JSON issue\" href=\"sourcecode\/jquery_jsonp\/jquery_json.html\" target=\"_blank\" rel=\"nofollow noopener noreferrer\">JSON service from cross-domain<\/a>\u00a0by checking this demo.<\/p>\n<p>Oops! The drop-downs are not loading. Let check the error console in FireFox (from menu Tools &gt;&gt; Error Console).<\/p>\n<p>We see two error lines as below:<\/p>\n<dl id=\"tf-message\">\n<dd>\n<p style=\"text-align: left;\"><code>Error: [Exception... \"Access to restricted URI denied\"\u00a0 code: \"1012\" nsresult: \"0x805303f4 (NS_ERROR_DOM_BAD_URI)\"\u00a0 location: \"... Line: ...\"]<\/code><br \/><code>Source File: ....<\/code><br \/><code>Line: ...<\/code><\/p>\n<p><code>Security Error: Content at file:... may not load data from .....<\/code><\/p>\n<\/dd>\n<\/dl>\n<p style=\"text-align: left;\">Hmmm, this is a cross domain JSON data fetch issue. So, when you try to access a JSON data using Jquery\/AJAX call from a different domain, we see the browser slapping the above error message on our face.<\/p>\n<p>Where do we go from here?<\/p>\n<p><strong>JSONP comes to the party<\/strong><\/p>\n<p style=\"text-align: left;\">JSONP stands for JSON with Padding. It is a work around used to resolve the cross domain dynamic JSON fetch problems by wrapping the JSON data in a function. So, what we return is something like:<\/p>\n<pre class=\"language-javascript\"><code>functionName({\"java_programming\": [ { \"ky\": \"java_basics\", \"val\": \"Java Basics\" }, ...]})<\/code><\/pre>\n<p style=\"text-align: left;\">The function name is passed as a parameter. In Jquery, during the getJSON call we pass a parameter &#8216;callback=?&#8217;. Jquery support JSONP and automatically generations a function name. The callback is the parameter in which the function name is passed.<\/p>\n<p>Let us get to work. We want to modify the code for implementing JSONP.<\/p>\n<ul>\n<li style=\"text-align: left;\"><em>jquery_json.html<\/em>\u00a0: Rename this file to\u00a0<em>jquery_jsonp.html<\/em>for convention purpose. We will modify the jquery call in this HTML file to implement JSONP. The below code snippet highlights this call.\u00a0<\/li>\n<\/ul>\n<pre class=\"language-javascript\"><code>$.getJSON(\"http:\/\/www.stage3.tech-freaks.in\/sourcecode\/jquery_jsonp\r\n  \/getSiteJsonp.php?type=category&amp;callback=?\", function(json) {\r\n var catJson = json[sSec];\r\n var options = \"&lt;option value=\\\"select\\\"&gt;Select&lt;\/option&gt;\";<\/code><\/pre>\n<ul>\n<li style=\"text-align: left;\"><em>getSiteJSON.php:\u00a0<\/em>Rename\u00a0this file to\u00a0<em>getSiteJSONP.php<\/em>\u00a0to provide an informative file name. We modify the code to\u00a0return a padded JSON instead of simple JSON. The below snippet explains how the &#8216;callback&#8217; parameter is used to pad the JSON data with function name.<\/li>\n<\/ul>\n<pre class=\"language-php\"><code> \/\/echo $jsonData;\r\n echo $_GET['callback'].\"(\".$jsonData.\")\";<\/code><\/pre>\n<p>See <a title=\"JSONP Demo\" href=\"sourcecode\/jquery_jsonp\/jquery_jsonp.html\" target=\"_blank\" rel=\"nofollow noopener noreferrer\">JSONP in action<\/a>. See how the dropdowns get generated dynamically by fetching data from\u00a0<em>www.stage3.tech-freaks.in<\/em>.<\/p>\n<p>Download the complete\u00a0<a title=\"JSONP and Jquery sourcecode\" href=\"https:\/\/www.tech-freaks.com\/wp-content\/uploads\/2009\/06\/jsonp_src.zip\" target=\"_blank\" rel=\"nofollow noopener noreferrer\">PHP source for JSONP\u00a0<\/a>implementation\u00a0<em>(<span style=\"color: #0000ff;\">JSP Sourcecode for JSONP Implementation coming soon!<\/span>)<\/em>.<\/p>\n<p>You no longer have to implement all services in house inside your domain. You can use JSONP to fetch JSON data using services implemented outside your domain.<\/p>\n<p>Phew! The struggle finally ended. You deserve to put your feet up for sometime and enjoy a cup of coffee!<\/p>\n","protected":false},"excerpt":{"rendered":"<p>The workshop is for This workshop is dedicated to all those who are stuck with cross-domain communication issue trying to [&hellip;]<\/p>\n","protected":false},"author":1,"featured_media":0,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"site-sidebar-layout":"default","site-content-layout":"","ast-site-content-layout":"default","site-content-style":"default","site-sidebar-style":"default","ast-global-header-display":"","ast-banner-title-visibility":"","ast-main-header-display":"","ast-hfb-above-header-display":"","ast-hfb-below-header-display":"","ast-hfb-mobile-header-display":"","site-post-title":"","ast-breadcrumbs-content":"","ast-featured-img":"","footer-sml-layout":"","theme-transparent-header-meta":"","adv-header-id-meta":"","stick-header-meta":"","header-above-stick-meta":"","header-main-stick-meta":"","header-below-stick-meta":"","astra-migrate-meta-layouts":"default","ast-page-background-enabled":"default","ast-page-background-meta":{"desktop":{"background-color":"var(--ast-global-color-5)","background-image":"","background-repeat":"repeat","background-position":"center center","background-size":"auto","background-attachment":"scroll","background-type":"","background-media":"","overlay-type":"","overlay-color":"","overlay-opacity":"","overlay-gradient":""},"tablet":{"background-color":"","background-image":"","background-repeat":"repeat","background-position":"center center","background-size":"auto","background-attachment":"scroll","background-type":"","background-media":"","overlay-type":"","overlay-color":"","overlay-opacity":"","overlay-gradient":""},"mobile":{"background-color":"","background-image":"","background-repeat":"repeat","background-position":"center center","background-size":"auto","background-attachment":"scroll","background-type":"","background-media":"","overlay-type":"","overlay-color":"","overlay-opacity":"","overlay-gradient":""}},"ast-content-background-meta":{"desktop":{"background-color":"var(--ast-global-color-4)","background-image":"","background-repeat":"repeat","background-position":"center center","background-size":"auto","background-attachment":"scroll","background-type":"","background-media":"","overlay-type":"","overlay-color":"","overlay-opacity":"","overlay-gradient":""},"tablet":{"background-color":"var(--ast-global-color-4)","background-image":"","background-repeat":"repeat","background-position":"center center","background-size":"auto","background-attachment":"scroll","background-type":"","background-media":"","overlay-type":"","overlay-color":"","overlay-opacity":"","overlay-gradient":""},"mobile":{"background-color":"var(--ast-global-color-4)","background-image":"","background-repeat":"repeat","background-position":"center center","background-size":"auto","background-attachment":"scroll","background-type":"","background-media":"","overlay-type":"","overlay-color":"","overlay-opacity":"","overlay-gradient":""}},"footnotes":""},"categories":[7],"tags":[],"class_list":["post-81","post","type-post","status-publish","format-standard","hentry","category-javascript"],"_links":{"self":[{"href":"https:\/\/www.tech-freaks.com\/wp-json\/wp\/v2\/posts\/81","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/www.tech-freaks.com\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/www.tech-freaks.com\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/www.tech-freaks.com\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/www.tech-freaks.com\/wp-json\/wp\/v2\/comments?post=81"}],"version-history":[{"count":0,"href":"https:\/\/www.tech-freaks.com\/wp-json\/wp\/v2\/posts\/81\/revisions"}],"wp:attachment":[{"href":"https:\/\/www.tech-freaks.com\/wp-json\/wp\/v2\/media?parent=81"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/www.tech-freaks.com\/wp-json\/wp\/v2\/categories?post=81"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/www.tech-freaks.com\/wp-json\/wp\/v2\/tags?post=81"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}