jQuery jsonp and cross domain ajax

JSONP or “JSON with padding” provides a method to request data from a server having a different domain. Typical web browser prohibit cross domain request due to same origin policy.
jquery-jsonp

Jsonp example

Here is a simple example of jsonp which fetches json data from a different domain:

<html>
<head>
<title>JSONP example</title>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.0/jquery.js"></script>
</head>
<body>
<h1>JSONP example</h1>
Following data is from cross domain server:
<pre style="background-color:lightgray;" id="jsondata"></pre>
</body>
</html>
<script>
$.getJSON('http://htmlsb.com/api/jsonp.php?jsonp=?', function(data) {
  $("#jsondata").text(JSON.stringify(data));
  console.log(data);
});
</script>
refresh

Here is the server side php code which serves json data:

<?php
$function_name = $_GET['jsonp'];

$json_array = array();
$json_array['key1'] = "value1";
$json_array['key2'] = "value2";

echo "$function_name (\n";
print json_encode($json_array);
echo ");\n";
?>
Note that the parameter “jsonp” in request and the server side code is same. We can use any other name but it should be same on client and server side. Also note that the question mark (?) in jsonp=? is filled by a unique id (different for each request).

Jsonp and cache

Jquery requests are not cached. The mechanism uses different jsonp value and hence the callback function name. Here is a sample returned value from the server:

jQuery19008618064667098224_1372877021660 (
{"key1":"value1","key2":"value2"})

Note that it is a javascript code and function name if different for each call to avoid caching. In case you want to use cached response you can use lower lavel api jQuery.ajax() with cache=true.

Jsonp – security

Some comments on security:

  1. Here the server side code is written with the intention that it can be used with jsonp. So there is no security issue if server side code is written carefully.
  2. We should avoid serving any sensitive data like user personal data from server side jsonp code.
  3. We should also avoid any update logic in jsonp server side code.

Few points to note

  1. An upcoming modern alternative to jsonp is to use Cross origin resource sharing. It is still not supported by all browsers though.
  2. Jsonp works only for get requests as it uses javascript <script> tag for the request.
  3. On a side note, flash uses cross domain policy files  to control cross domain requests access.

 

Share this article: share on Google+ share on facebook share on linkedin tweet this submit to reddit

Comments

Click here to write/view comments