What is JSONP?

JavaScript

The short answer

JSONP (JSON with Padding) is an old technique for making cross-origin requests before CORS existed. It works by loading data through a <script> tag instead of an AJAX request. The server wraps the JSON data in a function call, and the browser executes it. It is mostly a historical technique — use CORS and fetch instead.

How it works

The browser can load scripts from any origin (the same-origin policy does not block <script> tags). JSONP exploits this:

// 1. Define a callback function
function handleData(data) {
console.log(data.name); // "John"
}
// 2. Load a script from another origin
const script = document.createElement('script');
script.src =
'https://api.example.com/user?callback=handleData';
document.body.appendChild(script);

The server responds with:

handleData({ name: 'John', age: 30 });

The browser executes this like any script, which calls handleData with the data.

Why it is not used anymore

  • Security risk — you are executing arbitrary code from another server. If the server is compromised, it can inject malicious code.
  • Only supports GET — no POST, PUT, or DELETE
  • No error handling — if the request fails, you get no error callback
  • CORS exists — CORS is the standard, secure way to make cross-origin requests

Interview Tip

Explain that JSONP was a hack to bypass the same-origin policy using script tags. Show the basic mechanism (callback function + script tag). Then say it is replaced by CORS. This is a history question — keep it brief.

Why interviewers ask this

This tests if you know the history of cross-origin requests. Understanding JSONP helps you appreciate why CORS was created and why modern security mechanisms exist.