JavaScript

coding learning websites codepractice

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 Objects

JS Classes & Modules

JS Async Programming

JS Advanced

JS HTML DOM

JS BOM (Browser Object Model)

JS Web APIs

JS AJAX

JS JSON

JS Graphics & Charts

JSON JSONP


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.

What Is JSONP

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.

Why JSONP Was Needed

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.

How JSONP Works

The JSONP process follows these steps:

  1. The client defines a callback function

  2. The client sends a request using a script tag

  3. The server wraps JSON data inside the callback

  4. The browser executes the returned JavaScript

  5. The callback function receives the data

This approach turns data into executable code.

Basic JSONP Structure

Server response format:

callbackFunction({
    "name": "Amit",
    "city": "Delhi"
});

The response is not pure JSON. It is JavaScript code that calls a function.

Simple JSONP Example

Step 1: Define a Callback Function

function handleResponse(data) {
    console.log(data.name);
    console.log(data.city);
}

Step 2: Load Data Using Script Tag

<script src="https://example.com/data?callback=handleResponse"></script>

When the script loads, the server sends data wrapped inside handleResponse().

JSONP Example with Dynamic Script Creation

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.

JSONP Example with API Data

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.

JSONP and Query Parameters

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.

JSONP with jQuery

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.

JSONP Practical Use Case

Example: Fetch Weather Data

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.

Limitations of JSONP

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.

Security Risks of JSONP

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.

JSONP vs AJAX

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.

JSONP vs CORS

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 in 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.

Best Practices for JSONP

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.

When to Avoid JSONP

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.

Real World Usage of JSONP

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.

Browser Support

JSONP works in all browsers because it relies on script tags. However, modern browser support for CORS makes JSONP mostly unnecessary.

Modern Alternatives to JSONP

Developers now prefer:

  • CORS enabled APIs

  • Fetch API

  • Server side API proxies

  • WebSockets

These solutions are more secure and flexible.

Summary of JSON JSONP

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.


Practice Questions

  1. Create a callback function displayUser(data) that prints the name and age from a JSONP response.

  2. Dynamically create a <script> tag to fetch JSONP data from https://example.com/api/user?callback=displayUser.

  3. Modify the callback function to display the JSONP data inside a <div> with id userData.

  4. Simulate a JSONP server response with the function call displayUser({ "name": "Vicky", "age": 28 }) and test your client code.

  5. Use JSONP to fetch a list of users from a server and dynamically create an unordered list <ul> showing all user names.

  6. Implement error handling by checking if the callback function receives data; display "No data found" if empty.

  7. Use jQuery’s $.getJSON() with callback=? to fetch JSONP data and log each user’s name in the console.

  8. Create a JSONP response for a list of products and write a client-side function that generates HTML cards for each product.

  9. Experiment with nested objects in JSONP (e.g., user with name and address object) and display both name and city in HTML.

  10. Compare a JSONP GET request with a standard fetch GET request to a server with CORS enabled; observe differences in browser behavior.


Try a Short Quiz.

coding learning websites codepractice

No quizzes available.

JavaScript

online coding class codepractice

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 Objects

JS Classes & Modules

JS Async Programming

JS Advanced

JS HTML DOM

JS BOM (Browser Object Model)

JS Web APIs

JS AJAX

JS JSON

JS Graphics & Charts

Go Back Top