Yako
Yako

Reputation: 3484

How to use JSONP random callbacks with jQuery?

I'm struggling with jQuery to handle an Ajax/JSONP request.

I'm working with two different domains, and I make several simulatenous ajax calls. Therefore, I need to rely on a callback random name automatically generated by jQuery. This code would work if I added a jsonpCallback setting, but simultaneous calls would be conflictual (See here).

Following the documentation, I end up with this code:

var request = $.ajax({
        url: "http://www.myUrl.com/myScript.php?preventCache="+new Date(),
        data: {GETvariableName:"value"},
        contentType: "application/json",
        dataType:'jsonp'})
    .done(function(json) {
        console.dir(json.mydata);
        })
    .fail(function(e) {
        console.log(e.message);
        });

The PHP file serves something like this :

callback(
    {
        "mydata":
        [
        // my JSON content...
        ]
    }
);

I get this error message:

Uncaught ReferenceError: callback is not defined.

Fine, which function name should I use, as it is supposed to be automatically generated ?

Upvotes: 0

Views: 1017

Answers (2)

charlietfl
charlietfl

Reputation: 171690

php shouldn't define the callback, access value sent using $_GET['callback']

Upvotes: 1

Rickard
Rickard

Reputation: 2335

you should use the query parameter ?callback=function_name as the function name on the server. jQuery generates a random callback name and maps it to your .done function automatically.

Upvotes: 0

Related Questions