JSONP Tutorial

JSONP History

JSONP (JSON with Padding or JSON-P) was originally proposed by Bob Ippolito in 2005.

What is JSONP?

JSONP is a runnable JavaScript with callback.

Why JSONP?

When you make requests through JavaScript (XMLHttpRequest) across domains, you will receive an error "Request blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.'

As <script> tags are exempted from same-origin policies. Bob Ippolito uses this advantage to develop JSONP to share resources across foreign origins.

In the following example, we will send a request and receive a response within the same origin. But, you can also use this example for foreign origins.

Note: We provide server-side coding for both PHP and Node.js, you can choose your favorite.

Example

The following is the server-side coding using PHP.

Note: The response is wrapped inside a function call.

PHP Compiler
<?php echo "myFunction({ name: 'Hello ".$_GET['myname']."! Welcome to JSONP :)'})"); ?>

The following is the server-side coding using Node.js.

Note: The response is wrapped inside a function call.

Node.js Compiler
var express = require("express"); var app = express(); app.get("/",function(req, res){ res.sendFile('index.html',{root: __dirname}); }); app.get("/myjsonp.js",function(req, res){ res.send("myFunction({ name: 'Hello "+req.query.myname+"! Welcome to JSONP :)'})"); }); app.listen(8000, function(){ console.log("port is listening to 8000"); });

The following is the client-side coding to request and receive a response.

index.html
<!DOCTYPE html> <html lang="en-US"> <body> <h1>JSONP</h1> <p id="point"></p><script> function myFunction(data) { document.getElementById("point").innerHTML = data.name; } </script> <!-- For php use '"/myjsonp.php?myname=john"' --> <script src="/myjsonp.js?myname=john"></script> </body> </html>

Syntax

URL?key=value

Join Our Channel

Join our telegram channel to get an instant update on depreciation and new features on HTML, CSS, JavaScript, jQuery, Node.js, PHP and Python.

This channel is primarily useful for Full Stack Web Developer.

Share this Page

Meet the Author