JavaScript

JavaScript is a high-level, interpreted programming language that is widely used for web development. Initially designed as a client-side scripting language, it runs directly in web browsers, enabling dynamic and interactive user experiences. JavaScript can now be used for server-side development as well.

JSONP

15 April 2025 | Category:

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() or XMLHttpRequest, 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

FeatureJSONPCORS
HTTP MethodsOnly GETGET, POST, PUT, etc.
Error HandlingLimitedProper try/catch support
SecurityLess secure (script injection)More secure
Browser SupportAll browsersAll 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.