JavaScript JSON JSONP
JavaScript Basics

JavaScript JSON JSONP

JSONP

JSONP (JSON with Padding) is a method for sending JSON data without worrying about cross-domain issues. JSONP uses the <script> tag instead of the XMLHttpRequest object.

JSONP Intro

Requesting a file from another domain can cause cross-domain issues. However, requesting an external script from another domain does not have this problem. JSONP uses this advantage and requests files using the <script> tag.

<script src="demo_jsonp.php"></script>

The Server File

The server wraps the result inside 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 as a parameter. Make sure that the function exists on the client.

The JavaScript Function

The function named myFunc is located on the client and is ready to handle JSON data:

Example:

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

Creating a Dynamic Script Tag

The example above will execute the myFunc function when the page loads, based on where you put the script tag. To create the script tag only when needed:

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

To make the example dynamic by sending JSON to the PHP file and letting the PHP file return 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:

  1. Convert the request into an object using json_decode().
  2. Access the database and fill an array with the requested data.
  3. Convert the array into JSON using json_encode().
  4. Wrap the return object with myFunc().

JavaScript Example:

The myFunc function will be called 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 have no control over the server file, you can get the server file to call the correct function by passing a callback function as a parameter:

Example:

The PHP file will call the function you pass as a callback parameter:

let s = document.createElement("script");s.src = "jsonp_demo_db.php?callback=myDisplayFunction";document.body.appendChild(s);‍
Take a look into your desired course