Open In App

JavaScript | JSONP

What is JSONP?
The XMLHttpRequest(XHR) can be used to get the data from the server. Once the data is received in the browser it can use the JSON.parse() method to convert the received JSON string into JavaScript object. But, XHR comes with the same-origin security issue. This means, request a page from some domain, let’s say ADomain.com and then that page makes a XMLHttpRequest to get some data from BDomain.com, the browser denies this request. This is because the request was made to a different domain than the domain the page was served from. Only if the XMLHttpRequest is made to ADomain.com, it will receive back the data as XHR works only if the request is made to the same domain.

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:

Method to use JSONP:

Example 1:




<!DOCTYPE html>
<html>
<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);
        var para= document.getElementById("paragraphElement");
        for(var 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




<!DOCTYPE html>
<html>
<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
        var url = 
        "https://itunes.apple.com/search?term=taylor+swift&limit=5&callback=processData";
          
        // Create the script element dynamically through JavaScript 
        var scriptElement = document.createElement("script");
          
        // Set the src and id attributes of the script element
        scriptElement.setAttribute("src", url);
        scriptElement.setAttribute("id", "jsonp");
        var oldScriptElement= document.getElementById("jsonp");
          
        // Get the head element
        var 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. */
        var para = document.getElementById("paragraphElement");
          
        for(var 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]

Article Tags :