jQuery 1.2 introduced JSONP support, but on initial read of the release notes, I wasn’t completely sure what it was - so for anyone else that might want the Dr Seuss explanation.

JSONP is script tag injection, passing the response from the server in to a user specified function

[I’ve published 38 videos for new developers, designers, UX, UI, product owners and anyone who needs to conquer the command line today.](https://training.leftlogic.com/buy/terminal/cli2?coupon=BLOG\&utm_source=blog\&utm_medium=banner\&utm_campaign=remysharp-discount)

*\*Updated 2014-11-22:\*\* to show secure version of JSONP based on \[Metal Toad post]\(http\://www\.metaltoad.com/blog/using-jsonp-safely) and \[Andrew Betts’s feedback]\(https\://remysharp.com/2007/10/08/what-is-jsonp#comment-1707138872).

How you can use JSONP[](#how-you-can-use-jsonp)

You need to mould both your request and response to handle JSONP - and in doing so, you can have cross domain JSON requests.

Your server will need to return the response as JSON, but also wrap the response in the requested call back, something like this in PHP (hosted on http://myotherserver.com):

// where $_GET['callback'] = 'randomFn123'
$cb = $_GET['callback'];
if (preg_match('/\W/', $cb)) {
  // if $_GET['callback'] contains a non-word character,
  // this could be an XSS attack.
  header('HTTP/1.1 400 Bad Request');
  exit();
}
header('Content-type: application/javascript; charset=utf-8');
echo "/**/typeof ".$cb."==='function' && ".$cb."(".json_encode($data).")";
// prints: /**/typeof randomFn123==='function' && randomFn123({"name":"Remy", "id":"10", "blog":"http://remysharp.com"});

The jQuery script would be:

$.ajax({
  dataType: 'jsonp',
  data: 'id=10',
  url: 'http://myotherserver.com/getdata',
  success: function () {
    // do stuff
  },
});

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

Example in the Wild[](#example-in-the-wild)

[Twitter’s JavaScript blog plugin](/2007/05/18/add-twitter-to-your-blog-step-by-step/) works in exactly the same way. You create a function to handle the data from Twitter, and insert a script tag. Once the script is inserted, it calls the function passing the Twitter data as a JSON object.

How it works in jQuery[](#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.

Potential Problems[](#potential-problems)

  1. Security. There’s documents out on the web that can help, but as a cursory check, I would check the referrer in the server side script.

  2. There’s no error handling. The script injection either works, or it doesn’t. If there’s an error from the injection, it’ll hit the page, and short of a window wide error handler (bad, bad, very bad), you need to be sure the return value is valid on the server side.

Published 8-Oct 2007 under #code & #javascript & #jquery & #json & #jsonp. [Edit this post](https://github.com/remy/remysharp.com/blob/main/public/blog/what-is-jsonp.md)

Comments

Lock Thread

Login

Add Comment[M ↓   Markdown]()

[Upvotes]()[Newest]()[Oldest]()

![](<https://download.remysharp.com/comments/avatars/Andrew Betts.jpg>)

Andrew Betts

0 points

9 years ago

Hi Remy. Really old post, but I was searching for best practice on JSONp callback filtering and found [a link](%5Bhttp://www.metaltoad.com/bl…​%5D\(http://www.metaltoad.com/blog/using-jsonp-safely\)) to this post cited as bad practice. You may want to update the code to recommend a more secure method, such as:

$cb = $_GET['jsonp_callback'];
if ($cb &amp;&amp; preg_match("/^\w+$/", $cb)) {
  echo "/**/ typeof ".$cb." ==='function' &amp;&amp; ".$cb."(".$data.");";
}

rem

0 points

9 years ago

rem

0 points

9 years ago

That’s actually great feedback, I’ll get on that. I’ve been using the same technique with all our new jsonp callbacks too.

?

Anonymous

0 points

10 years ago

Request you to pls elaborate a bit more the exact difference between json and jsonp or if they are related in some way.

?

Anonymous

0 points

12 years ago

You is the man, this was driving me nuts…​ can’t believe we’re hacking such basic requirements.

?

Anonymous

0 points

13 years ago

Can someone explain why you need to have this dependent on a server-side (php, perl, whathaveyou) GET request? While I can see a certain security concern being addressed, it also still leaves a truck-sized hole. it’d be nice to be able to access a simple flat .json file. Found Angus Croll has made a nice modification for security purposes here, btw: http://bit.ly/exPYvE

?

Anonymous

0 points

13 years ago

@Derek : You can use json\_encode included in the most of PHP 5 configurations to convert an array or any types of vars into json compatible string.

?

Anonymous

0 points

13 years ago

I think the essence of JSONP can be summarized by 'cross domain data exchange'. If you aren’t doing cross-domain, you don’t need JSONP

?

Anonymous

0 points

13 years ago

Thanks for the example, however, there were a couple things I didn’t understand.

First, Is getdata your PHP file?

Second, getDataAsJSON is not a PHP function and there seems to be almost no documentation on it.

Thanks

?

Anonymous

0 points

13 years ago

best one line explanation of JSONP i’ve seen. thanks.

?

Anonymous

0 points

14 years ago

Remy, you’re a godsend. After hours of searching you have finally shown me the light with this 1 line:

echo $_GET['jsonp_callback'] . '(' . $data . ');';

Nobody was properly explaining how the server-side needed to prepend the callback variable.

Thanks again.

?

Anonymous

0 points

14 years ago

I’ve been trying to use JSONP and it is very confusing. Not one example I’ve seen explains it totally.

What is "getdata" in your URL? I have a page and I’m displaying a page on another domain inside a frame. The page is a search engine results page which is hosted by another site.

What I want to do is make AJAX calls that return HTML and JSON from within the hosted page (inside a frame in my main page) via JavaScript that is on my webserver.

From what I can tell, JSON-P will do the trick but I’m finding it difficult to understand the examples I’ve seen due to things not being explained completely.

Any help?

?

Anonymous

0 points

14 years ago

Shameless plug for my jsonp plugin here: [http://code.google.com/p/jq…​;](http://code.google.com/p/jquery-jsonp/)

Thought it was relevant ;)

?

Anonymous

0 points

14 years ago

Thanks for this Remy. I’d been looking all over the place trying to set up jsonp on my own server to transport data to one of my other sites. I was using jQuery’s getJSON method on the client side but was not wrapping the function in the automatically created callback function on the server side. Finally clicked when I read through this post.

?

Anonymous

0 points

15 years ago

Hello,

very nice feature. But my server will need to return the response as JSON in Perl - not PHP.\ Can you help me, what would be the syntax for the Perl-Script?

Thx for help,

Rob

?

Anonymous

0 points

15 years ago

Here’s a C CGI that turns GET requests into POST requests with a target URL of your choosing - [http://github.com/alandiper…​;](http://github.com/alandipert/jsonptunnel/tree/master)

This basically lets you POST to off-site URLs.

?

Anonymous

0 points

15 years ago

I’m using JSONP and it works great. Thanks. Is this considered a 'hack' or 'legitimate'? You mention security. Are there problems for the site running the javascript, or just the server receiving the GET?

?

Anonymous

0 points

15 years ago

I didn’t know the server code had to be modified as well. Now I understand how JSONP works. Thanks

?

Anonymous

0 points

16 years ago

thx ramy, u help me out from the trouble.

5 hours just to figure out this line:\ echo $\_GET\['jsonp\_callback'] . '(' . $data . ');';

:p

tx u so much..

?

Anonymous

0 points

16 years ago

@Ryan - you’re right, I can’t think of a way to use a POST to get a JSONP response. If you’re trying to write a REST API or something similar, you might want to send the POST, ignore the response, and use a GET JSONP to test for changes.

Does that help?

?

Anonymous

0 points

16 years ago

So one thing I’m noticing as a potential problem is the lack of support for the POST method. If I’m adding a comment or article via a webservice that provides JSONP support, I can’t work outside the limitations of GET. Any thoughts on this?

?

Anonymous

0 points

16 years ago

Good tip here on JSONP — I’m going to look into it further.

One thing: checking the referrer is basically useless from a security perspective, as it’s provided by the client and very easy to forge.

[Commento](https://commento.io)