JSON JSONP

JS Tutorial

JS Version

JS Objects

JS Function

JS Classes

JS Async

JS HTML DOM

JS Browser BOM

JS Web API

JS AJAX

JS JSON

JS vs JQUERY

JS Graphics

JSON JSONP

JSONP is a method used for sending JSON data without caring about cross-domain issues.

JSONP does not use the XMLHttpRequest object.

JSONP uses the <script> tag instead.

JSONP Intro

JSONP full form is JSON with Padding.

Requesting a file from another domain can cause problems, due to the cross-domain policy.

Requesting an external script from another domain does not cause any problem.

JSONP uses this advantage and requests files using the script tag instead of the XMLHttpRequest object.

<script src=”demo_jsonp.php”>

The Server File

The file on the server wraps the result inside a function call:

<?php

$myJSON = ‘{“name”:”John”, “age”:30, “city”:”New York”}’;

echo “myFunc(“.$myJSON.”);”;

?>

The result is used to return a call to a function named “myFunc” with the JSON data as a parameter.

The JavaScript function

The function named “myFunc” is found on the client, and ready to handle JSON data:

Example

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

Output

Request JSON using the script tag

The PHP file returns a call to a function that will handle the JSON data.

John

Creating a Dynamic Script Tag

The example above executes the “myFunc” function while the page is loading, based on where you put the script tag, which is not very satisfying.

The script tag should only be created when needed

Example

<!DOCTYPE html>

<html>

<body>

<h2>Click the Button.</h2>

<p>A script tag with an src attribute is created and placed in the document.</p>

<p>The PHP file returns a call to a function with the JSON object as a parameter.</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>

Dynamic JSONP Result

The examples above are static.

Create the example dynamic by sending JSON to the PHP file, and let the PHP file return a JSON object based on the information it gets.

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, with

the PHP function json_decode().

Access the database, and fill an array with the requested data.

Add the array to an object.

Convert the array into JSON using the json_encode() function.

Wrap “myFunc()” around the return object.

 Javascript Example

<!DOCTYPE html>

<html>

<body>

<p>A script tag with an src attribute is created and placed in the document.</p>

<p>The PHP file returns a call to a function with an object as a parameter.</p>

<p id=”demo”></p>

<p>Try changing the table property from “customers” to “products”.</p>

<script>

const obj = { table: “customers”, limit: 3};

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>

Output

A script tag with an src attribute is created and placed in the document.

The PHP file returns a call to a function with an object as a parameter.

Alfreds Futterkiste

Ana Trujillo Emparedados y helados

Antonio Moreno Taqueria

Callback Function

The server file sometimes offers a callback function as a parameter:

Example

<!DOCTYPE html>

<html>

<body>

<h2>Request With a Callback Function</h2>

<p>The PHP file returns a call to the function you send 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>

Output

Request With a Callback Function

The PHP file returns a call to the function you send as a callback.

John