Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

AJAX with JSONP returns error Callback is Undefined

Here is my ajax call. I know the headers are correct because when I access the url directly it gives me something like this: jsonpCallback({"id":"274"})

But when I make the ajax call - it is saying Uncaught ReferenceError: jsonpCallback is not defined

$.ajax({
    url: 'http://localhost:9000/product/rest/company?' + $('form').serialize(),
    type: 'GET',
    crossDomain: true, // enable this
    dataType: 'jsonp',
    jsonpCallback: 'callback',
    success: function(data) {
        console.log(data);
    },
    error: function(err) {
        console.log(err);
    }
}).then(function(data) {
    console.log(data);
});

What am I doing wrong in this call?

like image 651
itamar Avatar asked Oct 27 '15 11:10

itamar


1 Answers

The server is giving back the JSONP resource using the wrong callback function name.

You wrote that the response from the server is something like:

jsonpCallback({"id":"274"})

The JSON data is wrapped into the padding function jsonpCallback whose name is not matching with the parameter specified in the Ajax request. It should be:

callback({"id":"274"})

in fact callback is the name passed as jsonpCallback option in the jQuery AJAX call

jsonpCallback: 'callback',

Editing the server side script that generates the response to apply a proper callback name will fix things.

Alternatively you can fix things on "the other side" by making the ajax call parameter matching with the function name in the response:

jsonpCallback: 'jsonpCallback',


The above is the "quick fix".

However it is strongly reccomended that you don't specify a custom callback name (using the parameter jsonpCallback).

Instead let jQuery generate a random callback name for each request.

The server side script will then parse the GET parameter callback and use the name passed for the callback function name that wraps the JSON data.

For example if you make a request like:

http://localhost:9000/product/rest/company?param=123

jQuery will add a parameter to the query string like this:

http://localhost:9000/product/rest/company?param=123&callback=jQuery1520422276

(it actually uses a longer callback name)

The server should parse callback and build up the response using the value passed as the padding function that wraps the JSON returned data:

jQuery1520422276({"id":"274"})

like image 81
Paolo Avatar answered Sep 20 '22 01:09

Paolo