-
Hajipur, Bihar, 844101
Hajipur, Bihar, 844101
JS Basics
JS Variables & Operators
JS Data Types & Conversion
JS Numbers & Math
JS Strings
JS Dates
JS Arrays
JS Control Flow
JS Loops & Iteration
JS Functions
JS Functions
Function Definitions
Function Parameters
Function Invocation
Function Call
Function Apply
Function Bind
Function Closures
JS Arrow Function
JS Objects
JS Objects
JS Object Properties
JS Object Methods
JS Object Display
JS Object Constructors
Object Definitions
Object Get / Set
Object Prototypes
Object Protection
JS Classes & Modules
JS Async Programming
JS Advanced
JS Destructuring
JS Bitwise
JS RegExp
JS Precedence
JS Errors
JS Scope
JS Hoisting
JS Strict Mode
JS this Keyword
JS HTML DOM
DOM Intro
DOM Methods
DOM Document
DOM Elements
DOM HTML
DOM Forms
DOM CSS
DOM Animations
DOM Events
DOM Event Listener
DOM Navigation
DOM Nodes
DOM Collections
DOM Node Lists
JS BOM (Browser Object Model)
JS Web APIs
Web API Intro
Web Validation API
Web History API
Web Storage API
Web Worker API
Web Fetch API
Web Geolocation API
JS AJAX
AJAX Intro
AJAX XMLHttp
AJAX Request
AJAX Response
AJAX XML File
AJAX PHP
AJAX ASP
AJAX Database
AJAX Applications
AJAX Examples
JS JSON
JSON Intro
JSON Syntax
JSON vs XML
JSON Data Types
JSON Parse
JSON Stringify
JSON Objects
JSON Arrays
JSON Server
JSON PHP
JSON HTML
JSON JSONP
JS Graphics & Charts
When working with JavaScript and APIs, developers often face restrictions related to cross domain requests. Browsers follow a security rule called the same origin policy, which prevents web pages from requesting data from a different domain. Before modern solutions like CORS became common, JSONP was widely used to solve this problem. Understanding JSONP is important because it explains how cross domain data sharing evolved and why modern approaches exist today.
In this tutorial, you will learn what JSONP is, why it was used, how it works, its syntax, detailed examples, limitations, security concerns, best practices, and real world use cases.
JSONP stands for JSON with Padding. It is a technique used to request data from a server located on a different domain by using a script tag instead of traditional AJAX requests.
JSONP works because browsers allow script files to be loaded from any domain. By wrapping JSON data inside a JavaScript function call, the server sends executable JavaScript code instead of plain JSON. The browser executes this code automatically.
In simple words, JSONP is a workaround to bypass cross domain restrictions by using script tags.
JSONP became popular because earlier browsers did not support cross origin resource sharing. Developers needed a way to:
Load data from third party APIs
Access cross domain resources
Build mashup applications
Fetch remote data without server proxies
JSONP allowed developers to fetch data from external servers without violating browser security rules.
The JSONP process follows these steps:
The client defines a callback function
The client sends a request using a script tag
The server wraps JSON data inside the callback
The browser executes the returned JavaScript
The callback function receives the data
This approach turns data into executable code.
Server response format:
callbackFunction({
"name": "Amit",
"city": "Delhi"
});
The response is not pure JSON. It is JavaScript code that calls a function.
function handleResponse(data) {
console.log(data.name);
console.log(data.city);
}
<script src="https://example.com/data?callback=handleResponse"></script>
When the script loads, the server sends data wrapped inside handleResponse().
Instead of static script tags, developers often use JavaScript to create them dynamically.
function loadData() {
let script = document.createElement("script");
script.src = "https://api.example.com/user?callback=showUser";
document.body.appendChild(script);
}
function showUser(data) {
console.log(data.name);
}
This allows better control over when the request is made.
Assume the server returns data like this:
showData({
"id": 1,
"product": "Mobile",
"price": 12000
});
Client side code:
function showData(data) {
console.log(data.product);
console.log(data.price);
}
The browser executes this automatically.
Most JSONP APIs expect a callback parameter.
Example request URL:
https://api.example.com/items?callback=displayItems
The server reads the callback name and returns data accordingly.
jQuery simplified JSONP usage.
$.ajax({
url: "https://api.example.com/users",
dataType: "jsonp",
success: function(data) {
console.log(data);
}
});
jQuery handles script creation and cleanup internally.
function showWeather(data) {
console.log(data.temperature);
console.log(data.city);
}
<script src="https://weatherapi.com/data?callback=showWeather"></script>
This was commonly used before CORS became standard.
JSONP has several limitations that restrict its use.
Only supports GET requests
Cannot send POST data securely
No proper error handling
Server must support JSONP
Data is executed as code
These limitations made JSONP unsuitable for many applications.
JSONP introduces security risks because it executes remote code.
Vulnerable to XSS attacks
Malicious scripts can run
No content type validation
Difficult to secure sensitive data
Because of these risks, JSONP should not be used for confidential information.
Key differences include:
JSONP bypasses same origin policy
AJAX follows browser security rules
JSONP uses script tags
AJAX uses XMLHttpRequest or Fetch
JSONP supports only GET
AJAX supports multiple HTTP methods
AJAX is safer and more flexible.
CORS is the modern replacement for JSONP.
CORS allows secure cross domain requests
JSONP executes code directly
CORS supports all HTTP methods
JSONP lacks proper error handling
Most modern APIs use CORS instead of JSONP.
Error handling is difficult in JSONP.
One workaround is setting a timeout.
let timeout = setTimeout(function() {
console.log("Request failed");
}, 5000);
If the callback is not executed, the request is assumed to fail.
If JSONP must be used:
Use trusted API providers
Avoid sensitive data
Use unique callback names
Remove script tags after execution
Prefer modern alternatives
These steps reduce risks.
Avoid JSONP when:
Security is a priority
POST requests are required
Modern browsers are supported
You control the server
In such cases, use CORS or server side proxies.
JSONP was commonly used in:
Old third party APIs
Early social media integrations
Public data feeds
Legacy web applications
Today, its usage is very limited.
JSONP works in all browsers because it relies on script tags. However, modern browser support for CORS makes JSONP mostly unnecessary.
Developers now prefer:
CORS enabled APIs
Fetch API
Server side API proxies
WebSockets
These solutions are more secure and flexible.
JavaScript JSONP was an important technique that allowed developers to fetch cross domain data before modern security standards were introduced. By wrapping JSON data inside a callback function and loading it through a script tag, JSONP bypassed the same origin policy. However, it comes with serious limitations and security risks, including lack of error handling and vulnerability to malicious code. While JSONP is largely replaced by CORS and modern APIs, understanding it helps developers appreciate the evolution of web security and choose safer approaches for cross domain communication today.
Create a callback function displayUser(data) that prints the name and age from a JSONP response.
Dynamically create a <script> tag to fetch JSONP data from https://example.com/api/user?callback=displayUser.
Modify the callback function to display the JSONP data inside a <div> with id userData.
Simulate a JSONP server response with the function call displayUser({ "name": "Vicky", "age": 28 }) and test your client code.
Use JSONP to fetch a list of users from a server and dynamically create an unordered list <ul> showing all user names.
Implement error handling by checking if the callback function receives data; display "No data found" if empty.
Use jQuery’s $.getJSON() with callback=? to fetch JSONP data and log each user’s name in the console.
Create a JSONP response for a list of products and write a client-side function that generates HTML cards for each product.
Experiment with nested objects in JSONP (e.g., user with name and address object) and display both name and city in HTML.
Compare a JSONP GET request with a standard fetch GET request to a server with CORS enabled; observe differences in browser behavior.
JS Basics
JS Variables & Operators
JS Data Types & Conversion
JS Numbers & Math
JS Strings
JS Dates
JS Arrays
JS Control Flow
JS Loops & Iteration
JS Functions
JS Functions
Function Definitions
Function Parameters
Function Invocation
Function Call
Function Apply
Function Bind
Function Closures
JS Arrow Function
JS Objects
JS Objects
JS Object Properties
JS Object Methods
JS Object Display
JS Object Constructors
Object Definitions
Object Get / Set
Object Prototypes
Object Protection
JS Classes & Modules
JS Async Programming
JS Advanced
JS Destructuring
JS Bitwise
JS RegExp
JS Precedence
JS Errors
JS Scope
JS Hoisting
JS Strict Mode
JS this Keyword
JS HTML DOM
DOM Intro
DOM Methods
DOM Document
DOM Elements
DOM HTML
DOM Forms
DOM CSS
DOM Animations
DOM Events
DOM Event Listener
DOM Navigation
DOM Nodes
DOM Collections
DOM Node Lists
JS BOM (Browser Object Model)
JS Web APIs
Web API Intro
Web Validation API
Web History API
Web Storage API
Web Worker API
Web Fetch API
Web Geolocation API
JS AJAX
AJAX Intro
AJAX XMLHttp
AJAX Request
AJAX Response
AJAX XML File
AJAX PHP
AJAX ASP
AJAX Database
AJAX Applications
AJAX Examples
JS JSON
JSON Intro
JSON Syntax
JSON vs XML
JSON Data Types
JSON Parse
JSON Stringify
JSON Objects
JSON Arrays
JSON Server
JSON PHP
JSON HTML
JSON JSONP
JS Graphics & Charts
