JavaScript: How do I create JSONP?

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="https://stackoverflow.com/questions/1678214/data-service.php?callback=receiver"></script>

Leave a Comment