I am the client guy who sends the server guy a request. My final goal is to send the request in jsonp.
This is the server response I get when I send the request with ?accept=json (and get an invalid session error because it is not jsonp)
{"errorCode":-15,"errorDescription":"SessionNotFoundException - Session not found","success":false,"payload":null}
I can read it and it is fine.
However, this is the server response for ?accept=jsonp:
jQuery171024326910870149732_1351429007451({"action":"", "type":"", "callerId":""}, {"errorCode":0,"errorDescription":"OK","success":true,"payload":null});
it is in the form of these 2 objects which I don’t know how to read: {a},{b}.
When I use jQuery ajax call
the output of the server’s data is only the {a} part:
Object {action: "", type: "", callerId: ""}
My 2 questions are:
- Is a server response with 2 objects (
{a},{b}) is valid or not? Does the server guy makes a mistake by sending that kind of object or it is valid? - How do I read the jsonp object? what is wrong with my ajax call that I can’t seem to be reading it right?
This is the ajax call I use:
$.ajax({
url:url,
dataType:'jsonp',
success:function(data){
console.log("data is,"data")
//if the call was success
if (data.success) {
//if errors
} else {
}
}
}
In order to actually verify that the success callback cannot handle 2 arguments, I tried a simple test with a 2 arg function and 2 objects passed into it:
This succeeded, since I passed two separate objects, in JavaScript Object Notation, into a function that expects 2 arguments.
Next, I recreated an example response with a simple PHP script:
So, next step, I went ahead and modified the success callback so that it takes 2 arguments:
Now, here’s where I ran into a problem, as per the jQuery AJAX Success Handler docs:
The 2nd parameter of the success handler is always going to be the status of the response, so my output was “data is success” in the console, and the alert in the else block is undefined.
jQuery’s jsonp implementation was most certainly designed to handle a single object in the callback, as it substitutes a custom value for the callback query parameter, which the server uses as “padding” or a wrapper for the response, usually in the form “jQuery1232432423432432”. The success handler, as per the docs, takes 3 arguments, where the first is the object and the last 2 are supplied by jQuery. The padded function only takes 1 argument. Thus, jQuery cannot solve this problem.
However, there is a technique to still utilize the existing server side response, assuming you have no control over what the server generates.
The Solution: Use Script Tag Remoting, Without jQuery:
To call the function, use it in place of the $.ajax call, except pass in a named callback handler:
Make sure you define a custom, named success callback function: