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.
<!DOCTYPE html>
<html>
<body>
<h2>Request JSON using the script tag</h2>
<p>The PHP file returns a call to a function that will handle the JSON data.</p>
<p id="demo"></p>
<script>
function myFunc(myObj) {
document.getElementById("demo").innerHTML = myObj.name;
}
</script>
<script src="/demo_jsonp.php"></script>
</body>
</html>
<!DOCTYPE html>
<html>
<body>
<h2>Click the Button.</h2>
<p>A code is made with a link to a source and inserted into the document.</p>
<p>The PHP document sends back a request to a function with the JSON data inside it.</p>
<button onclick="clickButton()">Click me!</button>
<p id="demo"></p>
<script>
function clickButton() {
let s = document.createElement("script");
s.src = "/demo_jsonp.php";
document.body.appendChild(s);
}
function myFunc(myObj) {
document.getElementById("demo").innerHTML = myObj.name;
}
</script>
</body>
</html>
<!DOCTYPE html>
<html>
<body>
<p>A code section with a source attribute is formed and inserted into the document.</p>
<p>The PHP file responds with a request to execute a function, passing an object as an argument.</p>
<p id="demo"></p>
<p>Experiment with modifying the table feature from "customers" to "products".</p>
<script>
const obj = {
table: "customers",
limit: 10
};
let s = document.createElement("script");
s.src = "/jsonp_demo_db.php?x=" + JSON.stringify(obj);
document.body.appendChild(s);
function myFunc(myObj) {
let txt = "";
for (let x in myObj) {
txt += myObj[x].name + " <br> ";
}
document.getElementById("demo").innerHTML = txt;
}
</script>
</body>
</html>
<!DOCTYPE html>
<html>
<body>
<h2>Request With a Callback Function</h2>
<p>The PHP file gives back a request to the function you specify as a callback.</p>
<p id="demo"></p>
<script>
let s = document.createElement("script");
s.src = "/demo_jsonp2.php?callback=myDisplayFunction";
document.body.appendChild(s);
function myDisplayFunction(myObj) {
document.getElementById("demo").innerHTML = myObj.name;
}
</script>
</body>
</html>
<!DOCTYPE html>
<html>
<body>
<h2>Request With a Callback Function</h2>
<p>The PHP file gives back a request to the function you specify as a callback.</p>
<p id="demo"></p>
<script>
let s = document.createElement("script");
s.src = "demo_jsonp2.php?callback=myDisplayFunction"; // Ensure this matches the function defined below
document.body.appendChild(s);
function myDisplayFunction(myObj) {
document.getElementById("demo").innerHTML = myObj.name; // This will display 'John Doe'
}
</script>
</body>
</html>