Open In App

JavaScript JSONP

Last Updated : 03 Oct, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

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]

Next Article

Similar Reads