The workshop is for

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.

Introduction

This workshop is built up based on 'JSON with Jquery' 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).

Quick Recap

Let us have a quick recap of the example 'JSON with Jquery'. However, it is strongly recommended to have go through JSON with Jquery workshop just to get an idea of what the example deals with. Here is a summary:

  1. A HTML page has the Jquery code to access JSON and generate dynamic dropdowns.
  2. There are two predefined static JSON files one for category and another for articles.

Dynamically generated JSON files

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 the database.

The below code snippet highlights the change in the Jquery JSON call in the html file.

$.getJSON("http://www.stage3.tech-freaks.in/sourcecode/jquery_jsonp/
                      getSiteJson.php?type=category",  function(json) {
          var catJson = json[sSec];
          var options = "<option value=\"select\">Select</option>";
          for(i=0;i<catJson.length;i++) {

The below code snippets is a PHP code which generates JSON.

   $type = $_GET['type'];
    $jsonData = "";
    if($type=="category")
        $jsonData = "{\"java_programming\": [ { \"ky\": \"java_basics\", ....}]}";
    else
        $jsonData = "{\"java_basics\": [\"Java Hello World - Tech Programmer\", ...]}";
    echo $jsonData;

 You may want to check the working of the getSiteJSON.php by accessing the page directly with query parameter of 'type=category' or 'type=article' and see the JSON printed in the page.

Cross domain JSON fetch

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. 

For this workshop, we simulate this scenario by hosting the getSiteJSON.php in www.stage3.tech-freaks.in and the HTML page which fetches the JSON content using Jquery in www.tech-freaks.in.

Uploading files.....

Check JSON service from cross-domain by checking this demo.

Oops! The drop-downs are not loading. Let check the error console in FireFox (from menu Tools >> Error Console).

We see two error lines as below:

Error: [Exception... "Access to restricted URI denied"  code: "1012" nsresult: "0x805303f4 (NS_ERROR_DOM_BAD_URI)"  location: "... Line: ..."]
Source File: ....
Line: ...

Security Error: Content at file:... may not load data from .....

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.

Where do we go from here?

JSONP comes to the party

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:

functionName({"java_programming": [ { "ky": "java_basics", "val": "Java Basics" }, ...]})

The function name is passed as a parameter. In Jquery, during the getJSON call we pass a parameter 'callback=?'. Jquery support JSONP and automatically generations a function name. The callback is the parameter in which the function name is passed.

Let us get to work. We want to modify the code for implementing JSONP.

  • jquery_json.html : Rename this file to jquery_jsonp.htmlfor convention purpose. We will modify the jquery call in this HTML file to implement JSONP. The below code snippet highlights this call. 
$.getJSON("http://www.stage3.tech-freaks.in/sourcecode/jquery_jsonp
  /getSiteJsonp.php?type=category&callback=?", function(json) {
 var catJson = json[sSec];
 var options = "<option value=\"select\">Select</option>";
  • getSiteJSON.php: Rename this file to getSiteJSONP.php to provide an informative file name. We modify the code to return a padded JSON instead of simple JSON. The below snippet explains how the 'callback' parameter is used to pad the JSON data with function name.
 //echo $jsonData;
 echo $_GET['callback']."(".$jsonData.")";

See JSONP in action. See how the dropdowns get generated dynamically by fetching data from www.stage3.tech-freaks.in.

Download the complete PHP source for JSONP implementation (JSP Sourcecode for JSONP Implementation coming soon!).

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.

Phew! The struggle finally ended. You deserve to put your feet up for sometime and enjoy a cup of coffee!

We use cookies

We use cookies on our website. Some of them are essential for the operation of the site, while others help us to improve this site and the user experience (tracking cookies). You can decide for yourself whether you want to allow cookies or not. Please note that if you reject them, you may not be able to use all the functionalities of the site.