What is JSONP?
The **XMLHttpRequest (XHR)** is a tool used to retrieve data from a server. Once the data is received by the browser, it can be converted from a JSON string into a JavaScript object using the `JSON.parse()` method. However, XHR encounters an issue known as the **same-origin policy**. This security measure prevents a webpage served from one domain (e.g., `ADomain.com`) from making an XMLHttpRequest to retrieve data from a different domain (e.g., `BDomain.com`). The browser will block the request because the domains are different. XHR only works when the request is made to the same domain that served the original page (e.g., `ADomain.com`).
JSONP (JSON with Padding)
It is a way to retrieve data by avoiding the cross-domain issue. The script tag is used to do so.
Difference between JSON and JSONP:
JSON:
JavaScript uses JSON (JavaScript Object Notation) to exchange data over the network. It look closely at a JSON data, it simply is a JavaScript Object in a string format.
Example:
{"name":"GFG", "id":1, "articlesWritten":5}
JSONP:
JSONP is JSON with Padding. Here, padding means wrapping a function around the JSON before it comes back in the request.
Example:
GeeksFunction({"name":"GFG", "id":1, "articlesWritten":5});
Method to use JSONP:
- In HTML code, include the script tag. The source of this script tag will be the URL from where the data to be retrieve. The web services allow to specify a callback function. In the URL include the callback parameter in the end.
- When the browser comes across the script element, it sends HTTP request to the source URL.
- The server sends back the response with JSON wrapped in a function call.
- The JSON response, which is in the form of a string, is parsed by the browser and converted to a JavaScript object. The callback function is called and the generated object is passed to it.
Example 1:
html
<!DOCTYPE html>
<html>
<head>
<title>JSONP</title>
</head>
<body>
<p id="paragraphElement"></p>
<!-- The server returns a call to the callback function
(processData) that will handle the JSON data -->
<script>
function processData(myObj) {
console.log(myObj);
let para = document.getElementById("paragraphElement");
for (let i = 0; i < myObj.resultCount; i++) {
para.innerHTML = para.innerHTML + myObj.results[i].trackName
+ "<br>";
}
}
</script>
<!-- Calling the iTunes API to search for Jack Johnson's songs and return
the first five items -->
<script src=
"https://itunes.apple.com/search?term=jack+johnson&limit=5&callback=processData">
</script>
</body>
</html>
Output:
Better Together
Banana Pancakes
Sitting, Waiting, Wishing
Upside Down
Good People
Example 2: Add script element dynamically using JavaScript
HTML
<!DOCTYPE html>
<html>
<head>
<title>JSONP</title>
</head>
<body>
<p id="paragraphElement"></p>
<script>
window.onload = createScriptDynamically();
function createScriptDynamically() {
// Set the url to the web service API from where
// the data to be retrieve
let url =
"https://itunes.apple.com/search?term=taylor+swift&limit=5&callback=processData";
// Create the script element dynamically through JavaScript
let scriptElement = document.createElement("script");
// Set the src and id attributes of the script element
scriptElement.setAttribute("src", url);
scriptElement.setAttribute("id", "jsonp");
let oldScriptElement = document.getElementById("jsonp");
// Get the head element
let head = document.getElementsByTagName("head")[0];
if (oldScriptElement == null) {
/* If there is no script element then append
a new element to the head. */
head.appendChild(scriptElement);
}
else {
/* If there is already a element in the head,
then replace it with the new script element. */
head.replaceChild(scriptElement, oldScriptElement);
}
}
function processData(myObj) {
console.log(myObj);
/* Function to display the track name and the
genre name from the received data. */
let para = document.getElementById("paragraphElement");
for (let i = 0; i < myObj.resultCount; i++) {
para.innerHTML = para.innerHTML + myObj.results[i].trackName
+ "[" + myObj.results[i].primaryGenreName + "]" + "<br>";
}
}
</script>
</body>
</html>
Output:
Delicate [Pop]
Look What You Made Me Do [Pop]
Shake It Off [Pop]
You Belong With Me [Country]
Blank Space [Pop]
Similar Reads
JavaScript JSON
JSON (JavaScript Object Notation) is a lightweight data format for storing and exchanging data. It is widely used to send data between a server and a client. JSON is simple, language-independent, and easy to understand.JSON stands for JavaScript Object Notation.It is a lightweight, text-based data i
4 min read
Javascript | JSON PHP
JSON stands for the JavaScript Object Notation. It is used to exchanging and storing the data from the web-server. JSON uses the object notation of JavaScript. JavaScript objects can be converted into the JSON and receive JSON format text into the JavaScript objects. Converting the JavaScript object
7 min read
JavaScript JSON Parser
JSON (JavaScript Object Notation) is a popular lightweight data exchange format for sending data between a server and a client, or across various systems. JSON data is parsed and interpreted using a software component or library called a JSON parser. Through the JSON parsing process, a JSON string i
3 min read
JavaScript | JSON Arrays
The JSON Arrays is similar to JavaScript Arrays. Syntax of Arrays in JSON Objects: // JSON Arrays Syntax { "name":"Peter parker", "heroName": "Spiderman", "friends" : ["Deadpool", "Hulk", "Wolverine"] } Accessing Array Values: The Array values can be accessed using the index of each element in an Ar
2 min read
JavaScript JSON Objects
JSON (JavaScript Object Notation) is a handy way to share data. It's easy for both people and computers to understand. In JavaScript, JSON helps organize data into simple objects. Let's explore how JSON works and why it's so useful for exchanging information.const jsonData = { "key1" : "value1", ...
3 min read
JSON vs JavaScript Object
JSON (JavaScript Object Notation) and JavaScript Objects are important for handling data in JavaScript, but they serve different purposes. JSON is a lightweight data format for transferring data, while JavaScript Objects are in-program data structures used for manipulation and logic.What is JSON?JSO
2 min read
JavaScript JSON parse() Method
The JSON.parse() method is used to convert a JSON string into a JavaScript object. Itâs become important when dealing with data in JSON format, interacting with APIs, or storing data in the browser.It converts a JSON string into a JavaScript object.Throws a SyntaxError if the input string is not val
3 min read
How to Parse JSON in JavaScript ?
Parse JSON in JavaScript, accepting a JSON string as input and returning a corresponding JavaScript object with two methods, using JSON.parse() for parsing JSON strings directly and employing the fetch API to parse JSON responses from web APIs. These techniques are crucial for seamless data manipula
2 min read
JavaScript JSON stringify() Method
The JSON.stringify() method in JavaScript is used to convert JavaScript objects into a JSON string. This method takes a JavaScript object as input and returns a JSON-formatted string representing that object. Syntax: JSON.stringify(value, replacer, space);Parameters: value: It is the value that is t
3 min read
How to Master JSON in JavaScript?
JSON is a text format for representing structured data, typically in the form of key-value pairs. It primarily sends data between a server and a client, especially in web APIs.Objects are enclosed in curly braces {} and contain key-value pairs.Arrays are enclosed in square brackets [] and hold value
5 min read