Sobis
Sobis

Reputation: 1405

REST AJAX cross-domain not executing callback

I'm having a lot of trouble to execute cross domain REST call with Jquery ajax function.

Here is code:

 $.ajax({
            url: restUrl,
                type: 'GET',
                crossDomain : true,
                dataType: 'jsonp',
                jsonp: false,
                jsonpCallback: 'jsonpCallbackTest',
                error: function(xhr, status, error) {
                    console.log('not OK '+xhr);
                    console.log('not OK '+status);
                    console.log('not OK '+error);
                },
                success: function(jsonp) {
                    alert("success");
                }
            });

and this is what I get in Firebug console:

not OK [object Object] Init.js:872
not OK parsererror Init.js:873
not OK Error: jsonpCallbackTest was not called


What am I doing wrong?

regards Matej

Upvotes: 0

Views: 1859

Answers (1)

Darin Dimitrov
Darin Dimitrov

Reputation: 1038820

What am I doing wrong?

It's difficult to say from the code information you provided in your question. There could be many reasons. For example the remote REST webservice that you are trying to invoke returns a JSON response instead of JSONP.

Also you seem to have defined the jsonpCallbackTest function and yet you are using an anonymous success handler which are incompatible. Try like this:

$.ajax({
    url: restUrl,
    type: 'GET',
    jsonpCallback: 'jsonpCallbackTest',
    error: function(xhr, status, error) {
        console.log('not OK '+xhr);
        console.log('not OK '+status);
        console.log('not OK '+error);
    }
});

and then define the jsonpCallbackTest function:

function jsonpCallbackTest(jsonp) {
    alert("success");
}

You will also have to check the documentation of the remote web service how to specify the JSONP callback. Whether you could pass it as query string parameter.

It's usually preferred to leave jQuery pass a random callback function name to the web service:

$.ajax({
    url: restUrl,
    type: 'GET',
    dataType: 'jsonp',
    success: function(json) {
        alert("success");
    },
    error: function(xhr, status, error) {
        console.log('not OK '+xhr);
        console.log('not OK '+status);
        console.log('not OK '+error);
    }
});

Upvotes: 4

Related Questions