JSONP
15 April 2025 | Category: JavaScript
JSONP (JSON with Padding) is a method to request data from a server in a different domain — something that is normally restricted by the Same-Origin Policy in web browsers.
- It is not a built-in feature of JSON, but a technique using
<script>
tags. - JSONP is commonly used to make cross-domain HTTP requests before CORS (Cross-Origin Resource Sharing) became the standard.
🧠 How Does JSONP Work?
- Instead of using
XMLHttpRequest
, JSONP works by dynamically adding a<script>
tag to your HTML. - The script loads data from another domain.
- The server returns a function call with data as a parameter.
🔁 Example Structure of JSONP:
callbackFunction({"name":"Alice", "age":25});
🔹 Basic JSONP Example
🧩 Step 1: HTML + JavaScript Code (Client)
<!DOCTYPE html>
<html>
<head>
<title>JSONP Example</title>
</head>
<body>
<h2 id="name"></h2>
<script>
function handleData(data) {
document.getElementById("name").textContent = "Name: " + data.name;
}
// Dynamically add a script that loads data from another domain
const script = document.createElement('script');
script.src = "https://example.com/user?callback=handleData";
document.body.appendChild(script);
</script>
</body>
</html>
🧩 Step 2: Server Response (From https://example.com/user)
The server returns this JavaScript, not plain JSON:
handleData({"name":"Alice", "age":25});
So when the script loads, it executes the handleData()
function defined on the client.
⚠️ Why Not Use JSONP Today?
- Security Risk: JSONP can execute arbitrary JavaScript from external sources.
- No support for POST: Only works with GET requests.
- No error handling: Unlike
fetch()
orXMLHttpRequest
, it’s hard to detect errors. - JSONP has mostly been replaced by CORS and modern APIs.
✅ When JSONP Might Still Be Useful
- When working with very old APIs that don’t support CORS.
- When building legacy applications with old browser support.
- Testing with static external datasets.
🔁 JSONP vs CORS
Feature | JSONP | CORS |
---|---|---|
HTTP Methods | Only GET | GET , POST , PUT , etc. |
Error Handling | Limited | Proper try/catch support |
Security | Less secure (script injection) | More secure |
Browser Support | All browsers | All modern browsers |
✏️ Summary
- JSONP loads external data by injecting a
<script>
tag. - The server wraps JSON in a function (callback).
- The client defines the callback to receive the data.
- Useful for cross-origin requests without using CORS.