Page 1 of 1

JSONP

PostPosted: Sun Apr 08, 2012 11:46 pm
by silvester


A good data format to use then is JavaScript Object Notation, more commonly known as JSON. Providing data in the JSON format with PHP is simple to handle.

All you need to do on the server side is to set the content-type to application/json, encode your data using the json_encode function and output it.
<?php

header('Content-Type: text/javascript; charset=utf8');
header('Access-Control-Allow-Origin: http://www.example.com/');
header('Access-Control-Max-Age: 3628800');
header('Access-Control-Allow-Methods: GET, POST, PUT, DELETE');

$callback = $_GET['callback'];

$data = '{}'; // json string

echo $callback.'('.$data.');';

?>

The jQuery script would be:

$.ajax({
dataType: 'jsonp',
data: 'id=10',
jsonp: 'jsonp_callback',
url: 'http://example.com/<<pagename>>',
success: function () {
// do stuff
},
});

jQuery will change the url to include &jsonp_callback=jsonpmethod - but you can exclude it and it default to just 'callback'.

How it works in jQuery

jQuery attaches a global function to the window object that is called when the script is injected, then the function is removed on completion.

Note that if the request is being made to the same domain, then jQuery will switch it down to a straight Ajax request.

Re: JSONP

PostPosted: Mon Apr 09, 2012 6:45 am
by beniston
Simple but cool stuff. Very handy and useful. :D :lol: Its always good to share such things...