Curriculum
Course: JavaScript Basic
Login

Curriculum

JavaScript Basic

JSHome

0/216
Text lesson

JSONP JSONP

JSONP is a technique for sending JSON data without encountering cross-domain restrictions.

Unlike XMLHttpRequest, JSONP uses the <script> tag instead.

JSONP Intro

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 Server File

The file on the server wraps the result in a function call.

Example

<?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 JavaScript function

The function named “myFunc” is defined on the client side and is ready to process the JSON data.

Example

function myFunc(myObj) {
  document.getElementById(“demo”).innerHTML = myObj.name;
}

Creating a Dynamic Script Tag

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.

Example

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);
}

Dynamic JSONP Result

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 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:

  • Convert the request into an object using the PHP function json_decode().
  • Access the database and populate an array with the requested data.
  • Add the array to an object.
  • Convert the object into JSON using the json_encode() function.
  • Wrap the return object with the myFunc() function.

JavaScript Example

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;
}

Callback Function

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.

Example

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);