Home >Backend Development >PHP Tutorial >How to Overcome Cross-Domain JSON Communication with JSONP?
JSONP: Enabling Cross-Domain JSON Communication
Cross-domain JSON communication poses a challenge due to the Same-Origin Policy. JSONP (JSON with Padding) was introduced as a solution to this problem.
Creating a JSONP Callback API
To create a JSONP callback API, you need to:
Example in PHP:
<code class="php"><?php $data = '{}'; if (array_key_exists('callback', $_GET)) { header('Content-Type: text/javascript; charset=utf8'); header('Access-Control-Allow-Origin: http://www.example.com/'); $callback = $_GET['callback']; echo $callback . '(' . $data . ');'; } else { header('Content-Type: application/json; charset=utf8'); echo $data; } ?></code>
This code sends a JavaScript file that calls the specified callback function with the JSON data as the first argument.
Using the JSONP Service
To use the JSONP service: