Confused on how a JSONP request works

Asked
Active3 hr before
Viewed126 times

8 Answers

request
90%

The callback is a function YOU'VE defined in your own code. The jsonp server will wrap its response with a function call named the same as your specified callback function.,The function name parseResponse is passed to the server and somehow the data returned becomes parameters to this function,4) Now that this new script has been loaded from the remote server, it will now be executed, and the only thing it will do is a function call, parseResponse(), passing in the JSON data as the function call's only parameter.,Making statements based on opinion; back them up with references or personal experience.

1) Your code creates the JSONP request, which results in a new <script> block that looks like this:

<script src="http://server2.example.com/RetrieveUser?UserId=1234&jsonp=parseResponse"></script>

2) That new script tag is executed by your browser, resulting in a request to the JSONP server. It responds with

parseResponse({
   "Name": "Foo",
   "Id": 1234,
   "Rank": 7
});

3) Since this request came from a script tag, it's pretty much EXACTLY the same as if you'd literally placed

<script>
    parseResponse({"Name": "Foo", "Id" : 1234, "Rank": 7});
</script>

So somewhere else in your code, you'd have:

function parseResponse(data) {
   alert(data.Name); // outputs 'Foo'
}

Basically, JSONP is a way of bypassing the browser's same-origin script security policy, by having a 3rd party server inject a function call directly into your page. Note that this is by design highly insecure. You're depending that the remote service is honorable and doesn't have malicious intent. Nothing stops a bad service from returning some JS code that steals your banking/facebook/whatever credentials. e.g.... the JSONP response could've been

 internalUseOnlyFunction('deleteHarddrive');
load more v
88%

I am having trouble understanding the details of how a jsonp request works. I have read several sources including the wiki on jsonp and am still very confused on how the callback actually gets a hold of the function returned from the server when a jsonp call is made. For example, in the wiki, the source of the request is set as:,In interest of simplicity, this does not include error handling if the request fails. Use script.onerror if you need that.,There is no error handling for cross domain JSONP requests. Use jsonp plug-in available on Github https://github.com/jaubourg/jquery-jsonp that provides support for error handling.,The callback is a function YOU'VE defined in your own code. The jsonp server will wrap its response with a function call named the same as your specified callback function.

I am having trouble understanding the details of how a jsonp request works. I have read several sources including the wiki on jsonp and am still very confused on how the callback actually gets a hold of the function returned from the server when a jsonp call is made. For example, in the wiki, the source of the request is set as:

src = "http://server2.example.com/RetrieveUser?UserId=1234&jsonp=parseResponse"

What exactly does jsonp = parseResponse actually do/mean?? Then they go on to say that the payload is:

parseResponse({
   "Name": "Foo",
   "Id": 1234,
   "Rank": 7
});
load more v
72%

Let’s create a function called jsonp that will send the request in the JSONP fashion.,As you can see, there’s a shared variable called jsonpID — it will be used to make sure that each request has its own unique function name.,Finally, we append the <script> element to <head> in order to fire the request. <script> will send the request automatically once it is appended.,After providing the callback’s name in the query, we create a function in the global (window) context, which will be called once the response is parsed and executed.

Upon seeing this, many people would Google it just to find out that JSONP would be needed to bypass the same-origin policy. Then jQuery, ubiquitous back in the day, would swoop in with its convenient JSONP implementation baked right into the core library so that we could get it working by switching just one parameter. Many people never understood that what changed completely was the underlying mechanism of sending the request.

$.ajax({
   url: 'http://twitter.com/status/user_timeline/padraicb.json?count=10',
   dataType: 'jsonp',
   success: function onSuccess() {}
});
load more v
65%

     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 your browser with name of the pre-defined function along with parameter being passed that is the requested JSON data. When the script executes, the function is called along with JSON data, allowing the requesting page to receive and process the data.,You are right and I have edited the article. I tried to convey the Web Origin Access Issue and how to tackle it via JSONP in vanilla javascript as most developers use JQuery and ignore the behind the scene working. ,This loop hole of inserting the “script” from server side dynamically at run time is the secret behind JSONP technique.,JSONP bypasses the restrictions of the same origin policy by dynamic script injection.

Let’s create a function which accepts the URL as the parameter and constructs the script tag at runtime and inserting the source from the remote server. In JSONP each script tag inserted is an individual AJAX call this might lead to unnecessary consumption of memory so once the data is consumed we would remove the script tag dynamically.

function requestServerCall(url) { //Construct the script tag at Runtime
   var head = document.head;
   var script = document.createElement("script");
   script.setAttribute("src", url);
   head.appendChild(script);
   head.removeChild(script); // remove the script tag once inserted to avoid memory consumption
}
load more v
75%

The client JavaScript code to make a JSONP call looks like this:,The client will now have  script tag that gets added to the document and the script executes on load and in effect calls the callbackFunction with the parameter:,the result will be turned into (assuming the callback specified is callbackFunction):,The server is expected to return JSON data, but with a slight twist: It has to prepend the callback function name, which is passed as part of the url. The syntax for a JSONP Url is simply the URL with a jsonp= query string parameter that defines the the callback function:

The client JavaScript code to make a JSONP call looks like this:

function jsonp(url, callback, name, query) {
   if (url.indexOf("?") > -1)
      url += "&jsonp="
   else
      url += "?jsonp="
   url += name + "&";
   if (query)
      url += encodeURIComponent(query) + "&";
   url += new Date().getTime().toString(); // prevent caching        

   var script = document.createElement("script");
   script.setAttribute("src", url);
   script.setAttribute("type", "text/javascript");
   document.body.appendChild(script);
}

If you're implementing this in an ASPX.NET page it might look like this:

public partial class JSONP: System.Web.UI.Page {
   protected void Page_Load(object sender, EventArgs e) {
      if (!string.IsNullOrEmpty(Request.QueryString["jsonp"]))
         this.JsonPCallback();
   }

   public void JsonPCallback() {
      string Callback = Request.QueryString["jsonp"];
      if (!string.IsNullOrEmpty(Callback)) {
         // *** Do whatever you need
         Response.Write(Callback + "( {\"x\":10 , \"y\":100} );");
      }

      Response.End();
   }
}
load more v
40%

My understanding is that JSONP is required in order to allow cross domain requests. And, in part, it works by wrapping the JSON data within a callback function, thus making it an object.,I'm creating an iOS / Droid app using AJAX, jQuery, and Phonegap. The backend is a Drupal 7 site serving content via web services. I'm a little confused about the necessity for a JSONP callback, though.,However, what I'm finding is that I can send the JSONP request without a callback, and parse the data via jQuery without the callback function. So the JSONP data looks exactly like JSON data.,Yes, definitely. The callback is substantial to the definition of JSON-with-padding. Without, it is just JSON.

FYI, here is the jQuery AJAX code:

$.ajax({
   type: 'GET',
   cache: false,
   url: 'http://www.example.com/mobile/menu/devel-gosto.jsonp',
   dataType: 'jsonp',
   timeout: menuLoadTimeout,
   success: function(data) {
      menu = populateSlider(data.tree, 0);
   }
});
22%

The way JSONP works is that it dynamically adds a < script >,The way JSONP works is that it dynamically adds a < script > tag into the header of your HTML file. When your dynamically generated script tag (by jQuery) is executed by your browser, it returns a script from the src url - which contains a call to your callback function (whose name is also generated internally by jQuery if it is an anonymous function).,So here they being say that data cant be extracted from script tag?,How to use jQuery's JSONP to get around the cross domain issues when loading external scripts by using an AJAX request that has a callback function.

This is the code that worked:

   $.ajax({
      url: mainLink,
      type: "GET",
      dataType: "jsonp",
      success: function(data) {
         console.log(data);
         // and other stuff i do with the data i get 
      },
      xhrFields: {
         withCredentials: false
      }
   }) // end ajax
load more v
60%

Twitter's JavaScript blog plugin works in exactly the same way. You create a function to handle the data from Twitter, and insert a script tag. Once the script is inserted, it calls the function passing the Twitter data as a JSON object.,jQuery attaches a global function to the window object that is called when the script is injected, then the function is removed on completion.,JSONP is script tag injection, passing the response from the server in to a user specified function,You need to mould both your request and response to handle JSONP - and in doing so, you can have cross domain JSON requests.

Your server will need to return the response as JSON, but also wrap the response in the requested call back, something like this in PHP (hosted on http://myotherserver.com):

// where $_GET['callback'] = 'randomFn123'
$cb = $_GET['callback'];
if (preg_match('/\W/', $cb)) {
   // if $_GET['callback'] contains a non-word character,
   // this could be an XSS attack.
   header('HTTP/1.1 400 Bad Request');
   exit();
}
header('Content-type: application/javascript; charset=utf-8');
echo "/**/typeof ".$cb.
"==='function' && ".$cb.
"(".json_encode($data).
")";
// prints: /**/typeof randomFn123==='function' && randomFn123({"name":"Remy", "id":"10", "blog":"http://remysharp.com"});
load more v

Other "request-undefined" queries related to "Confused on how a JSONP request works"