Skip to content Skip to sidebar Skip to footer

Pass Additional Parameter To A Jsonp Callback

For a project of mine I need to do multiple calls to a (remote) API using JSONP for processing the API response. All calls use the same callback function. All the calls are generat

Solution 1:

Your options are as follows:

  1. Have the server put the ID into the response. This is the cleanest, but often you cannot change the server code.
  2. If you can guarantee that there is never more than one JSONP call involving the ID inflight at once, then you can just stuff the ID value into a global variable and when the callback is called, fetch the id value from the global variable. This is simple, but brittle because if there are every more than one JSONP call involving the ID in process at the same time, they will step on each other and something will not work.
  3. Generate a unique function name for each JSONP call and use a function closure associated with that function name to connect the id to the callback.

Here's an example of the third option.

You can use a closure to keep track of the variable for you, but since you can have multiple JSON calls in flight at the same time, you have to use a dynamically generated globally accessible function name that is unique for each successive JSONP call. It can work like this:

Suppose your function that generate the tag for the JSONP is something like this (you substitute whatever you're using now):

functiondoJSONP(url, callbackFuncName) {
   var fullURL = url + "&" + callbackFuncName;
   // generate the script tag here
}

Then, you could have another function outside of it that does this:

// global varvar jsonpCallbacks = {cntr: 0};


functiongetDataForId(url, id, fn) {
    // create a globally unique function namevar name = "fn" + jsonpCallbacks.cntr++;

    // put that function in a globally accessible place for JSONP to call
    jsonpCallbacks[name] = function() {
        // upon success, remove the namedelete jsonpCallbacks[name];
        // now call the desired callback internally and pass it the idvar args = Array.prototype.slice.call(arguments);
        args.unshift(id);
        fn.apply(this, args);
    }

    doJSONP(url, "jsonpCallbacks." + name);
}

Your main code would call getDataForId() and the callback passed to it would be passed the id value like this followed by whatever other arguments the JSONP had on the function:

getDataForId(123, "http://remote.host.com/api?id=123", function(id, /* other args here*/) {
    // you can process the returned data here with id available as the argument
});

Solution 2:

There's a easier way. Append the parameter to your url after '?'. And access it in the callback function as follows.

var url = "yourURL";
    url += "?"+"yourparameter";
    $.jsonp({
        url: url,
        cache: true,
        callbackParameter: "callback",
        callback: "cb",
        success: onreceive,
        error: function () {
            console.log("data error");
        }
    });

And the call back function as follows

functiononreceive(response,temp,k){
  var data = k.url.split("?");
  alert(data[1]);   //gives out your parameter
 }

Note: You can append the parameter in a better way in the URL if you already have other parameters in the URL. I have shown a quick dirty solution here.

Solution 3:

This is a year old now, but I think jfriend00 was on the right track, although it's simpler than all that - use a closure still, just, when specifying the callback add the param:

http://url.to.some.service?callback=myFunc('optA')

http://url.to.some.service?callback=myFunc('optB')

Then use a closure to pass it through:

functionmyFunc (opt) {
    var myOpt = opt; // will be optA or optBreturnfunction (data) {
        if (opt == 'optA') {
            // do something with the data
        }
        elseif (opt == 'optB') {
            // do something else with the data
        }
    }
}

Post a Comment for "Pass Additional Parameter To A Jsonp Callback"