Understanding JSONP – With Javascript and jQuery Examples

So by reading the article, Understanding JSON and JSON with Javascript you have learned a lot about JSON, now we’ll expand it by learning JSONP With Javascript and jQuery on cross-domain ajax request.

In this article we’ll use Javascript to work with JSON, so… before going any further, it would be better if you have read the article: JSON with Javascript, it discusses all about JSON in the javascript environment.

I. Same Origin Policy Limitation

When the JSON comes from the same domain, then it will be easy to retrieve it, but if it is in a different domain, then thing become more complicated.

Why?

This is because we CAN NOT retrieve that data through the ajax request (using XMLHttpRequest objects), this is happened not only for JSON data but all data from different domains.

How could it happen?

This is happened because there is a “same origin policy” limitation, which means the script is only allowed to access data on the same origin (source), which includes: (1) the same protocol (same http/https), (2) same domain, and (3) same port, this is a global agreement and have been implemented by all browsers.

Same origin policy is applied for security reasons, for example: if we open an e-banking tab and in another tab we open a web page containing malicious script, then the script will freely access our e-banking browser’s data (cookies).

An example of same origin policy limitation, in webdevzoom.com, I create a file named json-remote-jagowebdev.php that contains the following code:

$.ajax({
  url: 'http://jagowebdev.com/wp-content/demo/last_article/',
  dataType: 'json',
  success: function(data) {
    console.log(data);
  },
  error: function(xhr) {
    console.log(xhr.responseText);
  }
})

The above script pulls the last 5 articles from jagowebdev.com. If I run the script, I’ll get the following error:

Same Origin Policy Error

Same Origin Policy Error

II. Introducing JSONP

To overcome the same origin policy restriction, we can use jsonp (JSON with padding).

This method is actually an old way, nowadays there is a newer method that is Cross-Origin Resource Sharing (CORS) where we simply add “Allow Origin” on the HTTP header.

However, jsonp is still popular and relevant to use, so it still worth to spend times to learn it here…

So.. what is JSONP?

JSONP is JSON with Padding (padding = javascript function call) or JSON that wrapped in a Javascript function call

So we can say that JSONP is an execution of a javascript function.

Notice the following example:

function json_data(obj) {
  alert (obj.website);
}

// This is the JSONP form
json_data({"website":"Jagowebdev.com"});

From the above example, it’s clear that JSONP is an execution of a function with JSON data as its argument.

So, because it is an execution of a javascript function, then we have to put it in the <script> tag.

Consider the following example:

1. Back to the previous example, in the jagowebdev.com, I create the file jsonp-static-jagowebdev.php with the following code:

json_data({"website":"Jagowebdev.com"});

2. Next, in the webdevzoom.com I create the file jsonp-static.html that contains the following code:

<html>
<head>
  <title>Understanding JSONP</title>
  <script>
    function json_data(obj) {
      alert(obj.website);
    }
  </script>
  <script src="http://jagowebdev.com/wp-content/demo/json-with-javascript/jsonp-static-jagowebdev.php"></script>
</head>
<body>
</body>
</html>

When we open the file in a browser, we’ll get the following result:

Retrieve JSONP Data Using Javascript

Retrieve JSONP Data Using Javascript

Demo: jsonp-static.html

In the above example, after the <script> retrieves data from http://jagowebdev.com/wp-content/demo/json-with-javascript/jsonp-static-jagowebdev.php, then it immediately executes the data by running the json_data() function.

So, if the function is not found, then we’ll get an error, for example, I replace the content of the file jsonp-static-jagowebdev.php with the custom_function({"website": "Jagowebdev.com"})

When we open the file jsonp-static.html, we’ll get the following error:

JSONP Error - Function Not Found

JSONP Error – Function Not Found

The error occurred because the script looks for the function custom_function() but can’t found it.

Using Dynamic Function Name With Dynamic Callback

So now, we know that jsonp is just an execution of a function, which in the previous example, the function name is json_data()

In practice, the name of this function is dynamic, depending on the query string of the URL, which generally named “callback”.

For example: if the function to be executed is my_function(), then the url is:

http://jagowebdev.com/wp-content/demo/json-with-javascript/jsonp-dynamic-jagowebdev.php?callback=my_function

To make the function name dynamic, we need to make a condition in accordance with the value of the callback.

For example: in the Jagowebdev.com, I create a file named jsonp-dynamic-jagowebdev.php with the following code:

<?php
$json = '{"website":"Jagowebdev.com"}';
if (@$_GET['callback'])
  echo @$_GET['callback'] . '(' . $json . ')';
else
  echo $json;

In the above script, if the url contains a callback, then the result is a jsonp, otherwise a json:

The use of dynamic callbacks is recommended, especially if the data is shared to the public so that they are free to use the function name, don’t need to bother to ask us or bother reading the documentation.

and… it also recommended if we use jQuery, we discussed later in this article…

Here’s an example of using dynamic callbacks:

<html>
<head>
  <title>Understanding JSONP</title>
  <script>
    function custom_function(obj) {
      alert(obj.website);
    }
  </script>
  <script src="http://jagowebdev.com/wp-content/demo/json-with-javascript/jsonp-dynamic-jagowebdev.php?callback=custom_function"></script>
</head>
<body>
</body>
</html>

When we execute the script, we’ll get the same result as the previous example, that is an alert containing the Jagowebdev.com text.

Demo: jsonp-dynamic.html

III. JSONP With JQuery

So now, we know how to work with jsonp, now, in this section, we’ll discuss how to handle JSONP using jQuery.

All we already know that in fact, our aim is to get only the JSON data, right?

Just because there is “same origin policy” limitation, we need to do some work round by using the JSONP method.

Well, if we use jQuery, behind the scene, it will take care all of this, so we can directly get the javascript object.

1. Dynamic Callback

In jQuery, when we want to pull json data from a different domain, we’ll have to decide whether we want to use a dynamic callback or static callback.

For dynamic callbacks, we don’t need to define the callback property in the $.ajax method, so the code becomes more simple, e.g.:

$.ajax({
  url: 'http://jagowebdev.com/wp-content/demo/json-with-javascript/jsonp-dynamic-jagowebdev.php',
  dataType: 'jsonp',
  success: function(obj) {
    // Result an Javascript objek
    alert(obj.website);
  },
  error: function(xhr, status, msg) {
    console.log('Status: ' + status + "\n" + msg);
  }
})

Demo: jquery-dynamic-callback.html

Note that in the above script, on the dataType property, we use “jsonp” instead of “json”.

When we open the file, we’ll get the same as the previous example, that is a windows alert that contain  “Jagowebdev.com” text

In the above script, jQuery will automatically add a callback query string to the URL with a random callback name, notice the following figure:

JSONP With jQuery - Dynamic Callback

JSONP With jQuery – Dynamic Callback

Because the callback is dynamic, then if on the targeted URL the function name is static, we’ll get an error.

For example, in the above script, if we change the url value to http://jagowebdev.com/wp-content/demo/json-with-javascript/jsonp-static-jagowebdev.php then we will get an error as follows:

JSONP With jQuery - Error Function Not Found

JSONP With jQuery – Error: Function Not Found

The above figure shows that jQuery adds a callback query string with the name:

jQuery33105103817664205077_1525995891123

so the requested url becomes:

http://jagowebdev.com/wp-content/demo/json-with-javascript/jsonp-static-jagowebdev.php?callback=jQuery33105103817664205077_1525995891123

Based on that callback name, jQuery provides a function with that name.

So, because jsonp in the above URL provides a static function that is json_data() then jQuery fails to execute it.

2. Static Callback

In addition to dynamic callbacks, for certain purposes, we want to use static callbacks (e.g. when using Flickr API).

In jQuery we can define the callback’s name by adding the jsonpCallback property to the $.ajax method, for example:

function json_data(obj) {
 alert(obj.website);
}

$.ajax({
  url: 'http://jagowebdev.com/wp-content/demo/json-with-javascript/jsonp-static-jagowebdev.php',
  dataType: 'jsonp',
  jsonpCallback: 'json_data',
  error: function(xhr, status, msg) {
    console.log('Status: ' + status + "\n" + msg);
  }
})

Notice that in the above code, we give the jsonpCallback property with the value json_data because we know that the targeted URL will generate jsonp with the function name json_data()

When we execute the script, jQuery will add a json_data query string to the url.

Note… Note that in the above script, we don’t employ the success property on the $.ajax method, why? because if succeeded, the result (JSON data) will automatically be passed to the json_data() function.

However, we can still use the success property to process the JSON data as the result (JSON data) also passed to it, for example:

function json_data(obj) {
 alert(obj.website);
}

$.ajax({
  url: 'http://jagowebdev.com/wp-content/demo/json-with-javascript/jsonp-static-jagowebdev.php',
  dataType: 'jsonp',
  jsonpCallback: 'json_data',
  success: function (obj) {
    alert(obj.website);
  },
  error: function(xhr, status, msg) {
    console.log('Status: ' + status + "\n" + msg);
  }
})
Sometimes, when using a static callback, the callback function outside the $.ajax method is not executed, so we need to use the success property to process the result

IV. JSONP in The Real World

In the real world, websites provide various forms of JSON data, but.. not all of them can be accessed using jsonp requests, so make sure the website supports jsonp, e.g. by adding a callback to the query string to the URL.

1. JSONP on Github.com

Github provides an API to retrieve the details of registered users.

To access that details, the URL format to use is https://api.github.com/users/user_name

Suppose we’ll take the details of the user Taylor Otwell (founder of Laravel Framework), the url is: https://api.github.com/users/taylorotwell

If we open the above URL using a browser, then we’ll get general JSON data

If we add a callback, e.g. https://api.github.com/users/taylorotwell?callback=custom_function then we’ll get the json data as follows:

custom_function({
  "meta": {
    "Content-Type": "application/javascript; charset=utf-8",
    ...
  },
  "data": {
   "login": "taylorotwell",
   ...
  }
})

By read at a glance, we know that the data is a JSONP, so we can pull the data using JSONP technique as we have discussed in section IV.

Demo: json-remote-github.php

2. JSONP on Flickr.com

Another example is Flickr data, one of the popular media for sharing photos.

Flickr provides an API URL that allows us to get their photo’s data, that is:  https://api.flickr.com/services/feeds/photos_public.gne

When we open the url in a browser, we’ll get the data in XML format.

In addition to XML, Flickr also provides data in json form, that is by adding the query string “format=json”, so the url becomes: https://api.flickr.com/services/feeds/photos_public.gne?format=json

The url provides data in jsonp format with jsonFlickrFeed() as the function name.

For Example: when we run the url https://api.flickr.com/services/feeds/photos_public.gne&tags=nature&format=json we get the following result:

jsonFlickrFeed({
  "title": "Recent Uploads tagged nature",
  "link": "https://www.flickr.com/photos/tags/nature/",
  ...data lain...
  "items": [
    {
      "title": "folded texture",
      "link": "https://www.flickr.com/photos/gnarlydog/27437163808/",
      "media": {
        "m": "https://farm1.staticflickr.com/808/27437163808_eb7d9f2341_m.jpg"
      },
      "date_taken": "2018-04-01T06:32:10-08:00",
      ...other data...
    },
    ...other data...
  ]
})

To be able to use that data, we must provide a function with the name jsonFlickrFeed(), for example:

function jsonFlickrFeed() {}

$.ajax({
  url: url_user, 
  dataType: 'jsonp',
  jsonpCallback: 'jsonFlickrFeed',
  success: function(obj) {
    // Some Code
  },
   error: function(xhr, status, msg) {
    console.log('Status: ' + status + "\n" + msg);
  }
})

Note… In the above script, I leave the jsonFlickrFeed(){} function empty, I don’t use it, it exists just because we must provide a function with the name jsonFlickrFeed. For processing the json data, I use the success property success: function(obj) as it more convenience.

DEMO: json-remote-flickr.php

Displaying Flickr Photos Using jQuery and AJAX

Displaying Flickr Photos Using jQuery and AJAX

Note… the script used in the demo page rather complicated because I add some code for lazy load images and masonry layout (works on widescreen) so the layout looks more neat and attractive.

Dynamic Callback on Flickr.com

Flickr also provides a dynamic function name (dynamic callback) for generated jsonp data, that is by adding a jsoncallback query string.

For example: to make the generated jsonp data use the function name custom_function(), the url is:

https://api.flickr.com/services/feeds/photos_public.gne?tags=nature&format=json&jsoncallback=custom_function

With this dynamic callback, we don’t need to write the function jsonFlickrFeed() For exercise, try to apply it in jQuery.

3. JSON on Medium.com – Not a JSONP

Not all websites support JSONP for data sharing.

For example, medium.com allow us to retrieve last posts data from a particular user (e.q steve yegge) by accessing the url: https://medium.com/@steve.yegge/latest?format=json.

That url generate data in JSON format rather than JSONP, so we can’t retrieve it directly using javascript or jQuery AJAX  (remember the same origin policy limitation), we have to do some work around instead, such as creating a proxy – discussed in another article.

V. Conclusion

If JSON data comes from different origin (different domain) has the JSONP (with P) form, then we can easily pull it using Javascript or jQuery ajax.

Otherwise…,  the situation becomes complicated because we have to do some work around, e.q using a proxy – discussed in another article.

Subscibe Now

Loves articles on webdevzoom.com? join our newsletter to get quality article right to your inbox. Nothing else, just quality stuff!!!

Our Commitment: We respect your privacy, we'll not share your credential to any party

Leave a comment

Like Us

Newsletter

Great information from webdevzoom.com right to your inbox

  1. Understanding JSONP – With Javascript and jQuery Examples

  2. JSON With Javascript and Ajax

  3. JSON From Database – PHP and MySQL

  4. JSON in HTML Document

  5. JSON With PHP – A Complete Guide

  6. Understanding JSON – A Comprehensive Guide

  7. 7 Best Free Online Image Compressor & Optimizer Tools – Compared & Tested

  8. 40+ Modern Free WordPress Themes For Blog in 2017 – Beautiful & Responsive

  9. Understanding Constant in PHP – Updated to PHP 7

  10. Understanding Variable in PHP – All PHP Version