Skip to content

Instantly share code, notes, and snippets.

@cowboy
Created September 7, 2011 14:28
Show Gist options
  • Star 10 You must be signed in to star a gist
  • Fork 5 You must be signed in to fork a gist
  • Save cowboy/1200708 to your computer and use it in GitHub Desktop.
Save cowboy/1200708 to your computer and use it in GitHub Desktop.
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
Copy link

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
Copy link
Author

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
Copy link

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
Copy link

thankyou, myproblem solved

@Bear4
Copy link

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