Monday, November 18, 2024
Google search engine
HomeLanguagesJavascriptJavaScript | JSONP

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:

  • 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:




<!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]

Whether you’re preparing for your first job interview or aiming to upskill in this ever-evolving tech landscape, neveropen Courses are your key to success. We provide top-quality content at affordable prices, all geared towards accelerating your growth in a time-bound manner. Join the millions we’ve already empowered, and we’re here to do the same for you. Don’t miss out – check it out now!

RELATED ARTICLES

Most Popular

Recent Comments