Press "Enter" to skip to content

Cross Domain Ajax Requests – JSONP example

JSONP or “JSON with padding” is a complement to the base JSON data format, a pattern of usage that allows a page to request data from a server in a different domain. As a solution to this problem, JSONP is an alternative to a more recent method called Cross-Origin Resource Sharing .
Under the same origin policy, a web page served from server1.example.com cannot normally connect to or communicate with a server other than server1.example.com. An exception is the HTML <script> element. Taking advantage of the open policy for <script> elements, some pages use them to retrieve Javascript code that operates on dynamically-generated JSON-formatted data from other origins. This usage pattern is known as JSONP.
Requests for JSONP retrieve not JSON, but arbitrary JavaScript code. They are evaluated by the JavaScript interpreter, not parsed by a JSON parser.
Example
File 1 Html File

<html>
<head>
 <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.4/jquery.min.js"></script>
 <script>
 function returnResponse(data){
 $('.response').append('<span>'+data.glossary.title+' <em>'+data.glossary.time+'</em></span> Received from: <span>'+data.glossary.server+'</span><br />');
 }
 $(document).ready(function(){
 $('#test_inp').keyup(function(){
 var myArguments = 'keyword='+$(this).val()+'&req=10$param=888';
 var crossDomainUrl = 'http://your-cross-domain.com/test/jsonp/get2.php?'+myArguments;
 $.ajax({ url: crossDomainUrl,
 dataType: 'jsonp',
 });
 });
});
 </script>
</head>
<body>
<input type="text" name="test_inp" id="test_inp" />
<p></p>
</body>
</html>

File 2
get2.php

<?php
$val = $_GET['keyword'];
$server = $_SERVER['SERVER_NAME'];
$time = strftime('%c');
echo('returnResponse(
{
 "glossary": {
 "title": "'.$val.'",
 "time":"'.$time.'",
 "server":"'.$server.'"
 }
}
) ')
?>

NOTE: Put both files in different domains and modify “crossDomainUrl” variable value according to the path for get2.php.