JSONP

Programming for Search Engines 101. An area for avid PHP and .NET developers to chat about Programming techniques and how to make better use of search engines.

Moderator: Moderators

JSONP

Postby silvester » Sun Apr 08, 2012 11:46 pm



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.
silvester
 
Posts: 89
Joined: Mon Nov 10, 2008 12:59 am

Re: JSONP

Postby beniston » Mon Apr 09, 2012 6:45 am

Simple but cool stuff. Very handy and useful. :D :lol: Its always good to share such things...
beniston
 
Posts: 502
Joined: Wed Nov 02, 2011 4:35 am
Location: Cochin
Tell us why you would like to become a WyseLabs Member:


Return to Programming

Who is online

Users browsing this forum: No registered users and 3 guests

cron