JSONP is a technique for sending JSON data without encountering cross-domain restrictions.
Unlike XMLHttpRequest, JSONP uses the <script>
tag instead.
JSONP stands for JSON with Padding. |
Requesting a file from another domain can lead to issues due to cross-domain policies.
However, requesting an external script from another domain does not face this restriction.
JSONP takes advantage of this by using the <script> tag instead of the XMLHttpRequest object to request files.
<script src=”demo_jsonp.php”> |
The file on the server wraps the result in a function call.
<?php $myJSON = ‘{ “name”:”John”, “age”:30, “city”:”New York” }’; echo “myFunc(“.$myJSON.“);”; ?> |
The result returns a call to a function named “myFunc” with the JSON data passed as a parameter.
Ensure that the function is defined on the client side.
The function named “myFunc” is defined on the client side and is ready to process the JSON data.
function myFunc(myObj) { document.getElementById(“demo”).innerHTML = myObj.name; } |
The example above executes the “myFunc” function as the page loads, depending on where the script tag is placed, which is not ideal.
The script tag should only be generated when necessary.
Create and insert the <script> tag when a button is clicked.
function clickButton() { let s = document.createElement(“script”); s.src = “demo_jsonp.php”; document.body.appendChild(s); } |
The examples above are still static.
Make the example dynamic by sending JSON to the PHP file, allowing the PHP file to return a JSON object based on the data it receives.
<?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).“)”; ?> |
The “myFunc” function will be invoked from the PHP file.
const obj = { table: “products”, 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; } |
When you don’t have control over the server file, how can you ensure the correct function is called?
In some cases, the server file provides a callback function as a parameter.
The PHP file will invoke the function that you pass as a callback parameter.
let s = document.createElement(“script”); s.src = “jsonp_demo_db.php?callback=myDisplayFunction“; document.body.appendChild(s); |