JSONP


JSONP is a way to send JSON data without concerns about different website boundaries.

JSONP doesn't utilize the XMLHttpRequest object.

JSONP employs the <script> tag instead of other methods.


JSONP Intro

JSONP is short for JSON with Padding.

Asking for a file from a different website can create issues because of cross-domain policy.

Asking for a script from a different website doesn't face this issue.

JSONP takes advantage of this by requesting files using the script tag instead of the XMLHttpRequest object.

<script src="demo_jsonp.php">

The JavaScript function

The function called "myFunc" is on the client side and is set up to manage JSON data.


Creating a Dynamic Script Tag

The example shown will run the "myFunc" function when the page loads, depending on where you place the script tag. However, this method might not be ideal.

Only create the script tag when necessary.


Dynamic JSONP Result

The examples provided are still very rigid and unchanging.

Make the sample interactive by sending JSON data to the PHP file. In return, the PHP file should provide a JSON object based on the received information.

PHP file

<?php
header("Content-Type: application/json; charset=UTF-8");
$obj = json_decode($_GET["x"], false);

$conn = new mysqli("myServer", "myUser", "myPassword", "Northwind");
$result = $conn->query("SELECT name FROM ".$obj->$table." LIMIT ".$obj->$limit);
$outp = array();
$outp = $result->fetch_all(MYSQLI_ASSOC);

echo "myFunc(".json_encode($outp).")";
?>

PHP File explained:

  • Transform the request into an object with PHP's functionjson_decode().
  • Retrieve information from the database and store it in an array as requested.
  • Insert the array into an object.
  • Transform the array into JSON with the json_encode() function.
  • Enclose the return object with the function "myFunc()."

Callback Function

When you can't control the server file, how can you make sure the server file calls the right function?

At times, the server file provides a callback function as a parameter.