kevin kevin - 2 months ago 27
Ajax Question

parse error callback function not called jquery ajax error?

I have been trying all the methods that i have seen in the stack overflow asked by other users before.But none of them are working.Please hoping any of you would point me in the right direction

$.ajax({
type: "get",
dataType:'jsonp',
params:jsonData,
jsonp:false,
jsonpCallback:"callbackfn",
headers: { "api_key": "u5FocU4xLq2rBfZ1ZSV8o81R2usYzUEM3NaCinnV"},
url: "http://localhost/url?name=xxx&email=xxxxxx@gmail.com",
success:function(){
alert("sucess function");
},
error: function(jqXHR, textStatus, errorThrown){
alert(textStatus + " and<br> " + errorThrown);
}
});
function callbackfn(data) {
alert(data);
}


the response is
{
"firstName":"John",
"lastName":"Doe"
}



Although the response is json,this rises an error


Parse error .callbackfn not called.

Answer

In order to use a custom callback function with JSONP, you must declare its scope to be global, i.e.

window.callbackfn = function(data) {
    alert(data);
};

Why?

This is because successful JSONP responses return a new JavaScript file, that is, a JavaScript function call encapsulated in <script> tags. Since each script is independently evaluated in the global scope, any script's function you would like to be made available to another script must also be declared in the global scope. Thus all JSONP callback functions should be global.


EDIT

According to OP, the solution found here: Return JSONP via AWS Lambda/API Gateway did the trick. Issue had to do with an improper server-side JSONP response.