I am trying to both create the Server and client side of a jsonp request, and I cannot seem to make it work. I’ve looked around at numerous guides, blog posts, etc, but pretty much everyone shows only the client side.
Here’s my client code
$.ajax({
dataType: 'application/json',
data: params,
jsonp: 'jsonpCallback',
url: settings.domain + '/httpext.dll?json_cc',
success: function (data) {
//determine the return status
},
error: function (response, status, error) {
//error handling
}
}); //end ajax
right now, the server is returning a hard coded value like this
jsonpCallback({"username":"meltingice","posts"1234});
My problem is that I cannot get the request and response to work together. Currently, the response is returning application/json, so if I change my request ro expect jsonp it errors with
Resource interpreted as script but transferred with MIME type application/json.
Uncaught ReferenceError: jsonpCallback is not defined
First off, as you can see, I have jsonpCallback defined.
Now, if I change the dataType to application/json, then I get this error
XMLHttpRequest cannot load http://myserver/httpext.dll?json_cc&sid=adsfhasjdkfhajksdghjk%3Basdhg&action=SALE&ccCard=&ccNum=&ccExMM=0&ccExYYYY=0&ccCVV2=&holdersName=&totalDue=0&dueDate=11%2F19%2F2010. Origin http://localhost:59905 is not allowed by Access-Control-Allow-Origin.
As you can see, it is not putting callback=? into the url. It’s rather frustrating.
How do I set up the server side so I can call it using jsonp? What do I need for the response type? How do I format the data returned so my client side code can pull back the data?
The reason this doesn’t work is because your server is always returning a hardcoded method name and your client is using an anonymous
successhandler. This cannot work. You need to configure your server to use the method name passed as argument or it will never invoke thesuccesscallback at the client. So once you configure your server to take into account thejsoncallbackquery parameter you could test it like this:Now the server will receive a request that might look like this:
and it should respond like this:
with proper
Content-Typeas well obviously (application/json).