Search code examples
jqueryjsonajaxjsonp

Paramer sent into in jsonpCallback function undefined


I'm executing this:

$.ajax({
  url: url,
  dataType: 'jsonp',
  jsonpCallback: function (data) { alert("jsonp call-back: " + data); },
  success: function (a, b, c, d) { alert("call ok"); },
  error: function (a, b, c, d) { alert(a.state() + " " + b + " " + c + " " + d); }
});

The problem is that I get data to be undefined in jsonpCallback function. I also noticed that in the console, I've got an error message about a missing semicolon before statement. When I click the link on the right, I see the JSON structure I'm trying to get.

  1. What did I miss in the call?
  2. How can I get the requested content into my JS code?

The admin claims that the server is exposed as JSON data provider and it's supposed to work. I haven't verified that myself but I have to assume it's so.


Solution

  • The jsonpCallback option for $.ajax lets you specify or generate the name of the function to use for the JSONP callback. It is not the actual callback. From the documentation:

    jsonpCallback

    Type: String or Function()

    Specify the callback function name for a JSONP request. This value will be used instead of the random name automatically generated by jQuery. It is preferable to let jQuery generate a unique name as it'll make it easier to manage the requests and provide callbacks and error handling. You may want to specify the callback when you want to enable better browser caching of GET requests. As of jQuery 1.5, you can also use a function for this setting, in which case the value of jsonpCallback is set to the return value of that function.

    (my emphasis)

    If you simply remove that option from your call, jQuery will auto-generate a unique name for you, and call your success function with the deserialized JSONP data.