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 cannot normally connect to or communicate with a server other than 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.
File 1 Html File

 <script src=""></script>
 function returnResponse(data){
 $('.response').append('<span>'+data.glossary.title+' <em>'+data.glossary.time+'</em></span> Received from: <span>'+data.glossary.server+'</span><br />');
 var myArguments = 'keyword='+$(this).val()+'&req=10$param=888';
 var crossDomainUrl = ''+myArguments;
 $.ajax({ url: crossDomainUrl,
 dataType: 'jsonp',
<input type="text" name="test_inp" id="test_inp" />

File 2

$val = $_GET['keyword'];
$server = $_SERVER['SERVER_NAME'];
$time = strftime('%c');
 "glossary": {
 "title": "'.$val.'",
) ')

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