JSONP stands for JSON with Padding.
Requesting a file from another domain can cause problems, due to cross-domain policy.
Requesting an external script from another domain does not have this problem.
JSONP uses this advantage, and request files using the script tag instead of the XMLHttpRequest
object.
Callback Function
When you have no control over the server file, how do you get the server file to call the correct function?
Sometimes the server file offers a callback function as a parameter:
Let's Learn
Step 1:
Create Index.php file and implement code as below
<button class="btn btn-info" onclick="clickButton()">Click me!</button> <h2 id="demo"></h2>
Step 2:
Create json_demo.php file and implement code as below.
<?php $myJSON = '{ "name":"Shiva", "age":30, "city":"New York" }'; echo "myDisplayFunction(".$myJSON.");"; //echo $myJSON; ?>
Step 3:
Now we implement java script to get data from database from php file.
<script> function clickButton() { var s = document.createElement("script"); s.src = "json_demo.php?callback=myDisplayFunction"; document.body.appendChild(s); } function myDisplayFunction(myObj) { document.getElementById("demo").innerHTML = myObj.name; } </script>
Complete Code For JSONP With Callback Function Using JavaScript
<!DOCTYPE html> <html> <head> <title>How To Use JSONP With Callback Function Using Java Script</title> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css"> </head> <body> <div class="container"> <br> <div class="text-center"> <h1 id="color" style="color: tomato">How To Use JSONP With Callback Function Using Java Script</h1> </div> <div class="well"> <button class="btn btn-info" onclick="clickButton()">Click me!</button> <h2 id="demo"></h2> </div> <script> function clickButton() { var s = document.createElement("script"); s.src = "json_demo.php?callback=myDisplayFunction"; document.body.appendChild(s); } function myDisplayFunction(myObj) { document.getElementById("demo").innerHTML = myObj.name; } </script> </div> </body> </html>