Question
What Is JSONP in JavaScript? Why It Was Created and How It Works
Question
I understand JSON as a data format, but I do not understand JSONP.
One definition says:
JSONP or "JSON with padding" is a JSON extension wherein a prefix is specified as an input argument of the call itself.
That is confusing to me because JSON is just a data format. There is no obvious "call" involved.
Another explanation says:
JSONP is script tag injection, passing the response from the server into a user-specified function.
I partly understand that, but I still do not see the full picture.
So what exactly is JSONP? Why was it created, what problem was it trying to solve, and why would someone use it?
For example, what is happening in a pattern like this?
function handleData(data) {
console.log(data);
}
const script = document.createElement('script');
script.src = 'https://example.com/data?callback=handleData';
document.body.appendChild(script);
Short Answer
By the end of this page, you will understand that JSONP is not a new data format, but a technique for loading data by wrapping JSON inside a JavaScript function call. It was created to work around older browser same-origin restrictions that blocked normal AJAX requests to other domains. You will learn how JSONP works, why it existed, its limitations, its security risks, and why modern applications usually use CORS instead.
Concept
JSONP stands for JSON with Padding.
The most important idea is this:
- JSON is plain data.
- JSONP is JavaScript code that calls a function and passes JSON data into it.
A normal JSON response looks like this:
{"name":"Alice","age":30}
A JSONP response looks like this:
handleData({"name":"Alice","age":30});
The handleData(...) part is the padding. The JSON data is wrapped in a function call.
Why JSONP was created
Older browsers enforced the same-origin policy for AJAX requests. That meant JavaScript on one website could not easily fetch data from another domain using XMLHttpRequest.
For example:
- A page on
https://myapp.comcould not make a normal AJAX request tohttps://api.example.com.
Mental Model
Imagine your web page is a house.
- JSON is like a sealed package left at the door. It contains data.
- AJAX is like sending someone through the front gate to pick up the package.
- The same-origin policy is a guard that says, "You cannot fetch packages from that other neighborhood."
But there is one exception:
- The guard allows newspapers from other neighborhoods to be delivered through the mail slot.
- A
<script>tag is that mail slot.
So instead of sending just a package of data, the other server sends a newspaper article that says:
handleData({"name":"Alice"});
Your page has already prepared a function named handleData, so when the script arrives, the browser reads it out loud and your function receives the data.
That is JSONP: using the browser's ability to load external scripts as a way to receive cross-domain data.
Syntax and Examples
Core pattern
Client-side code:
function handleData(data) {
console.log('Received:', data);
}
const script = document.createElement('script');
script.src = 'https://api.example.com/user?callback=handleData';
document.body.appendChild(script);
Possible server response:
handleData({"id":1,"name":"Alice"});
What each part does
- The page defines a global function such as
handleData. - The page creates a
<script>element. - The
srcpoints to another domain. - The URL includes a callback name.
- The server returns JavaScript that calls that function.
- The browser loads and executes that script.
Beginner-friendly example
Suppose you want weather data from another domain.
Step by Step Execution
Consider this code:
function handleData(data) {
console.log('Name:', data.name);
}
const script = document.createElement('script');
script.src = 'https://example.com/user?callback=handleData';
document.body.appendChild(script);
Assume the server responds with:
handleData({"name":"Alice"});
Step-by-step
1. Define the callback function
function handleData(data) {
console.log('Name:', data.name);
}
The page creates a function named handleData. This function will receive data later.
2. Create a script element
Real World Use Cases
Historical use cases
JSONP was commonly used for:
- Public APIs that needed to support browser access from any site
- Widgets embedded on third-party websites
- Mashups that combined data from several services on one page
- Search suggestions and autocomplete from external services
- Analytics or ad scripts that returned dynamic data
Example scenarios
1. Public API consumption
A news site might fetch headlines from another domain using JSONP.
2. Embeddable widgets
A stock ticker widget embedded on many websites could request live data from the provider's domain.
3. Third-party integrations
A page could show social media counts or public profile information from another service.
Where it is less suitable
JSONP was never ideal for:
- private data
- authenticated requests
- non-GET operations
- reliable error handling
That is one reason modern apps prefer fetch with CORS.
Real Codebase Usage
In real projects, JSONP usually appeared as a fallback or as a feature for older APIs.
Common patterns
1. Callback parameter convention
Servers often accepted query parameters like:
callback=myFunctionjsonp=myFunctioncb=myFunction
The backend inserted that function name into the response.
2. Dynamically generated callback names
To avoid naming collisions, developers often generated unique global functions:
const callbackName = 'jsonpCallback_' + Date.now();
window[callbackName] = function (data) {
console.log(data);
delete window[callbackName];
};
3. Cleanup after execution
After the callback ran, code often removed:
- the global callback function
- the injected
<script>element
This prevented memory leaks and duplicate calls.
4. Guard clauses
Developers often checked that the response had expected fields before using it:
Common Mistakes
1. Thinking JSONP is a data format
JSONP is not a replacement for JSON.
- JSON = data
- JSONP = JavaScript function call containing data
Broken assumption:
// Wrong idea: treating JSONP as plain JSON
const data = '{"name":"Alice"}';
Actual JSONP response:
handleData({"name":"Alice"});
2. Forgetting that the callback must exist globally
Because the response executes as script, the callback usually needs to be accessible on window.
Broken example:
(function () {
function handleData(data) {
console.log(data);
}
})();
If the server calls handleData(...), it may fail because handleData is not global.
Safer version:
Comparisons
JSON vs JSONP
| Feature | JSON | JSONP |
|---|---|---|
| Type | Data format | JavaScript technique |
| Example | {"name":"Alice"} | handleData({"name":"Alice"}); |
| Executable | No | Yes |
| Cross-domain workaround | No | Yes, historically |
| Security risk | Lower | Higher, because it executes script |
JSONP vs AJAX with CORS
| Feature | JSONP | AJAX/fetch with CORS |
|---|---|---|
| Transport style |
Cheat Sheet
Quick definition
- JSON: plain data format
- JSONP: JavaScript function call containing JSON data
- Purpose: old workaround for cross-domain browser restrictions
JSON example
{"name":"Alice"}
JSONP example
handleData({"name":"Alice"});
Basic flow
- Define a global callback function
- Create a
<script>tag - Set
srcto a URL with a callback parameter - Server returns JavaScript that calls your function
- Browser executes it
Typical client code
window.handleData = function (data) {
console.log(data);
};
const script = document.createElement('script');
script. = ;
..(script);
FAQ
Is JSONP the same as JSON?
No. JSON is a data format. JSONP is a technique where JSON data is wrapped inside a JavaScript function call.
Why was JSONP needed?
It was used to bypass old browser same-origin restrictions that blocked cross-domain AJAX requests.
Does JSONP still matter today?
Mostly for legacy systems. Modern applications usually use fetch or XMLHttpRequest with CORS.
Is JSONP safe?
It is less safe than plain JSON because it executes JavaScript from another domain. Only use it with trusted sources.
Can JSONP send POST requests?
No, not in the normal way. JSONP works through a <script> request, which is effectively GET-only.
Can any API be used with JSONP?
No. The server must explicitly support JSONP and return a callback-wrapped response.
What does "padding" mean in JSONP?
It means the JSON data is padded or wrapped with extra text: a function name and parentheses.
What replaced JSONP?
CORS became the standard solution for cross-origin browser requests.
Mini Project
Description
Build a small JSONP loader utility to understand how cross-domain script-based data loading works. This project demonstrates the full JSONP pattern: creating a callback, injecting a script tag, receiving data, handling timeouts, and cleaning up after the request.
Goal
Create a reusable jsonpRequest function that loads JSONP data from a URL and resolves it in a callback-based style.
Requirements
- Create a function that accepts a URL and a callback parameter name.
- Generate a unique global callback function name for each request.
- Inject a
<script>tag with the callback name added to the URL. - Call a success handler when data arrives.
- Clean up the script element and callback function after completion.
- Add timeout handling for requests that never respond.
Keep learning
Related questions
Deep Cloning Objects in JavaScript: Methods, Trade-offs, and Best Practices
Learn how to deep clone objects in JavaScript, compare structuredClone, JSON methods, and recursive approaches with examples.
Get Screen, Page, and Browser Window Size in JavaScript
Learn how to get screen size, viewport size, page size, and scroll position in JavaScript across major browsers with clear examples.
How JavaScript Closures Work: A Beginner-Friendly Guide
Learn how JavaScript closures work with simple explanations, examples, common mistakes, and practical use cases for real code.