kevin
kevin

Reputation: 87

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 protected]",
 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.

Upvotes: 4

Views: 2947

Answers (2)

citysurrounded
citysurrounded

Reputation: 674

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.

Upvotes: 1

Rob M.
Rob M.

Reputation: 36521

Make sure that your response from the server is a function call with the response data as the argument. It appears you are just outputting JSON, but JSONP expects a function call with the response data. Your server response should look like this:

callbackfn({
  "firstName":"John",
  "lastName":"Doe"
});

You have jsonp: false with a jsonpCallback and dataType: 'jsonp' - which is odd, because you are also supplying a jsonp callback. Perhaps if you don't need JSONP due to cross-origin requests, you should remove the jsonpCallback argument and just manually call that function with the response:

$.ajax({
   type: "get",
   dataType:'json',
   params:jsonData,
   headers: { "api_key": "u5FocU4xLq2rBfZ1ZSV8o81R2usYzUEM3NaCinnV"},
   url: "http://localhost/url?name=xxx&[email protected]",
   success:function(data){
     callbackfn(data);
   },
   error: function(jqXHR, textStatus, errorThrown){
       alert(textStatus + " and<br> " + errorThrown);
    }
});

Upvotes: 0

Related Questions