javascript tutorial - [Solved-5 Solutions] JSONP all about - javascript - java script - javascript array



Problem:

What is JSONP all about ?

Solution 1:

It's actually not too complicated...

Say you're on domain example.com, and we want to make a request to domain example.net. To do so, we need to cross domain boundaries, a no-no in most of browserland.

The one item that bypasses this limitation is <script> tags. When we use a script tag, the domain limitation is ignored, but under normal circumstances, we can't really do anything with the results, the script just gets evaluated.

Enter JSONP. When we make our request to a server that is JSONP enabled, we pass a special parameter that tells the server a little bit about our page. That way, the server is able to nicely wrap up its response in a way that our page can handle. For example, say the server expects a parameter called "callback" to enable its JSONP capabilities. Then our request would look like:

http://www.example.net/sample.aspx?callback=mycallback
click below button to copy the code. By JavaScript tutorial team

Without JSONP, this might return some basic JavaScript object, like so:

{ foo: 'bar' }
click below button to copy the code. By JavaScript tutorial team

However, with JSONP, when the server receives the "callback" parameter, it wraps up the result a little differently, returning something like this:

mycallback({ foo: 'bar' });
click below button to copy the code. By JavaScript tutorial team

As we can see, it will now invoke the method we specified. So, in our page, we define the callback function:

mycallback = function(data){
  alert(data.foo);
};
click below button to copy the code. By JavaScript tutorial team

And now, when the script is loaded, it'll be evaluated, and our function will be executed. Voila, cross-domain requests!

It's also worth noting the one major issue with JSONP: we lose a lot of control of the request. For example, there is no "nice" way to get proper failure codes back. As a result, we end up using timers to monitor the request, etc, which is always a bit suspect. The proposition for JSONRequestis a great solution to allowing cross domain scripting, maintaining security, and allowing proper control of the request. These days (2015), CORS is the recommended approach vs. JSONRequest. JSONP is still useful for older browser support, but given the security implications, unless we have no choice CORS is the better choice.

Solution 2:

Because we can ask the server to append a prefix to the returned JSON object. E.g function_prefix(json_object); in order for the browser to eval "inline" the JSON string as an expression. This trick makes it possible for the server to "inject" javascript code directly in the Client browser and this with bypassing the "same origin" restrictions.

In other words, we can have cross-domain data exchange. Normally, XMLHttpRequest doesn't permit cross-domain data-exchange directly (one needs to go through a server in the same domain)

Also worth noting: even though the server should be considered as "trusted" before attempting that sort of "trick", the side-effects of possible change in object format etc. can be contained. If a function_prefix (i.e. a proper js function) is used to receive the JSON object, the said function can perform checks before accepting/further processing the returned data.

Solution 3:

JSONP works by constructing a “script” element (either in HTML markup or inserted into the DOM via JavaScript), which requests to a remote data service location. The response is a javascript loaded on to our browser with name of the pre-defined function along with parameter being passed that is tht JSON data being requested. When the script executes, the function is called along with JSON data, allowing the requesting page to receive and process the data.

client side snippet of code

<!DOCTYPE html>
    <html lang="en">
    <head>
     <title>AvLabz - CORS : The Secrets Behind JSONP </title>
     <meta charset="UTF-8" />
    </head>
    <body>
      <input type="text" id="username" placeholder="Enter Our Name"/>
      <button type="submit" onclick="sendRequest()"> Send Request to Server </button>
    <script>
    "use strict";
    //Construct the script tag at Runtime
    function requestServerCall(url) {
      var head = document.head;
      var script = document.createElement("script");

      script.setAttribute("src", url);
      head.appendChild(script);
      head.removeChild(script);
    }

    //Predefined callback function    
    function jsonpCallback(data) {
      alert(data.message); // Response data from the server
    }

    //Reference to the input field
    var username = document.getElementById("username");

    //Send Request to Server
    function sendRequest() {
      // Edit with our Web Service URL
      requestServerCall("http://localhost/PHP_Series/CORS/myService.php?callback=jsonpCallback&message="+username.value+"");
    }    

  </script>
   </body>
   </html>
click below button to copy the code. By JavaScript tutorial team

Server side piece of PHP code

<?php
    header("Content-Type: application/javascript");
    $callback = $_GET["callback"];
    $message = $_GET["message"]." we got a response from server yipeee!!!";
    $jsonResponse = "{\"message\":\"" . $message . "\"}";
    echo $callback . "(" . $jsonResponse . ")";
?>

click below button to copy the code. By JavaScript tutorial team

Solution 4:

JSONP is a great away to get around cross-domain scripting errors. We can consume a JSONP service purely with JS without having to implement a AJAX proxy on the server side.

We can use the b1t.co service to see how it works. This is a free JSONP service that alllows we to minify our URLs. Here is the url to use for the service: http://b1t.co/Site/api/External/MakeUrlWithGet?callback=[resultsCallBack]&url=[escapedUrlToMinify]

whateverJavascriptName({"success":true,"url":"http://google.com","shortUrl":"http://b1t.co/54"});
click below button to copy the code. By JavaScript tutorial team

And thus when that get's loaded in our js as a src, it will automatically run whateverJavascriptName which we should implement as our callback function:

function minifyResultsCallBack(data)
{
    document.getElementById("results").innerHTML = JSON.stringify(data);
}
click below button to copy the code. By JavaScript tutorial team

To actually make the JSONP call, we can do it about several ways (including using jQuery) but here is a pure JS example:

function minify(urlToMinify)
{
   url = escape(urlToMinify);
   var s = document.createElement('script');
   s.id = 'dynScript';
   s.type='text/javascript';
   s.src = "http://b1t.co/Site/api/External/MakeUrlWithGet?callback=resultsCallBack&url=" + url;
   document.getElementsByTagName('head')[0].appendChild(s);
}

click below button to copy the code. By JavaScript tutorial team

Solution 5:

A simple example for the usage of JSONP.

client.html

    <html>
    <head>
   </head>
     body>


    <input type="button" id="001" onclick=gO("getCompany") value="Company"  />
    <input type="button" id="002" onclick=gO("getPosition") value="Position"/>
    <h3>
    <div id="101">

    </div>
    </h3>

    <script type="text/javascript">

    var elem=document.getElementById("101");

    function gO(callback){

    script = document.createElement('script');
    script.type = 'text/javascript';
    script.src = 'http://localhost/test/server.php?callback='+callback;
    elem.appendChild(script);
    elem.removeChild(script);


    }

    function getCompany(data){

    var message="The company we work for is "+data.company +"<img src='"+data.image+"'/   >";
    elem.innerHTML=message;
}

    function getPosition(data){
    var message="The position we are offered is "+data.position;
    elem.innerHTML=message;
    }
    </script>
    </body>
    </html>
click below button to copy the code. By JavaScript tutorial team

server.php

  <?php

    $callback=$_GET["callback"];
    echo $callback;

    if($callback=='getCompany')
    $response="({\"company\":\"Google\",\"image\":\"xyz.jpg\"})";

    else
    $response="({\"position\":\"Development Intern\"})";
    echo $response;

    ?>    

click below button to copy the code. By JavaScript tutorial team

Related Searches to javascript tutorial - JSONP all about