Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
JSONP "callback" param explanation, via basic PHP script.
<?PHP
# JSONP "callback" param explanation, via basic PHP script.
#
# "Cowboy" Ben Alman
# http://benalman.com/
# Set $data to something that will be serialized into JSON. You'll undoubtedly
# have your own code for this.
$data = array("some_key" => "some_value");
# Encode $data into a JSON string.
$json = json_encode($data);
# If a "callback" GET parameter was passed, use its value, otherwise null. Note
# that "callback" is a defacto standard for the JSONP function name, but it may
# be called something else, or not implemented at all. For example, Flickr uses
# "jsonpcallback" for their API.
$jsonp_callback = isset($_GET['callback']) ? $_GET['callback'] : null;
# If a JSONP callback was specified, print the JSON data surrounded in that,
# otherwise just print out the JSON data.
#
# Specifying no callback param would print: {"some_key": "some_value"}
# But specifying ?callback=foo would print: foo({"some_key": "some_value"})
print $jsonp_callback ? "$jsonp_callback($json)" : $json;
?>
@mathiasbynens

This comment has been minimized.

Copy link

@mathiasbynens mathiasbynens commented Sep 7, 2011

Don’t forget to send the appropriate Content-Type header! I’ve been using something like this for my JSON/JSONP needs:

<?php

header('Access-Control-Allow-Origin: *');

$callback = isset($_GET['callback']) ? preg_replace('/[^a-z0-9$_]/si', '', $_GET['callback']) : false;
header('Content-Type: ' . ($callback ? 'application/javascript' : 'application/json') . ';charset=UTF-8');

$data = array('some_key' => 'some_value');

echo ($callback ? $callback . '(' : '') . json_encode($data) . ($callback ? ')' : '');

?>

Made this into a gist with more comments: https://gist.github.com/mathiasbynens/5547352

@cowboy

This comment has been minimized.

Copy link
Owner Author

@cowboy cowboy commented Sep 7, 2011

I actually used this in my Simple PHP Proxy script, but forgot it here!

<?PHP

$is_xhr = strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest';
header('Content-type: application/' . ($is_xhr ? 'json' : 'x-javascript'));

?>```
@mathiasbynens

This comment has been minimized.

Copy link

@mathiasbynens mathiasbynens commented Sep 7, 2011

Not that it really matters*, but the official JavaScript MIME type is application/javascript nowadays (not application/x-javascript) as per RFC4329.

* Browsers don’t care about the Content-Type header in this case.

@andibastian

This comment has been minimized.

Copy link

@andibastian andibastian commented May 3, 2017

thankyou, myproblem solved

@Bear4

This comment has been minimized.

Copy link

@Bear4 Bear4 commented Feb 1, 2018

mathiasbynens thanks 💯 it's proper solution. For me works.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment