JavaScript: How do I create JSONP?

Teddi picture Teddi · Nov 5, 2009 · Viewed 46.9k times · Source

I have a two domains, example1.com and example2.com

From example1.com, I would like call a JSON API I have on example2.com. Knowing that this is not allowed, it occurred to me - this is exactly why JSONP was created.

Question is, how do I modify my JSON API to make it JSONP capable?

Basically, how do I create the callback api?

UPDATE

My server side language is PHP

Answer

mauris picture mauris · Nov 5, 2009

It is simple. Simply accept a parameter called callback in the GET.

Then wrap the callback JavaScript function around your data.

Example in PHP:

<?php

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

if(array_key_exists('callback', $_GET)){

    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'];
    echo $callback.'('.$data.');';

}else{
    // normal JSON string
    header('Content-Type: application/json; charset=utf8');

    echo $data;
}

It's idea is to simply return a JavaScript file which calls the callback function with the JSON object as the first parameter of the JavaScript callback function.

You can use the built-in json_encode() function to create JSON strings (which $data in our example above contains) from arrays and objects in PHP.

To use the JSONP service, you can use the <script> tag:

<script>
    function receiver(data){
        console.log(data);
    }
</script>
<script src="data-service.php?callback=receiver"></script>