Cross domain AJAX called with JSONP returns plain JSON

I have encountered a problem with an API I want to use. The API returns plain JSON but its a cross domain AJAX call so I have to use jsonp.

                type: "GET",
                url: url + query,
                contentType: "application/json",
                dataType: "jsonp",
                success: function(data){

The problem is when I change the dataType to "json" an error occurs:

No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'X' is therefore not allowed access.

This is because its a cross domain ajax call. But when it is jsonp it says:

Uncaught SyntaxError: Unexpected token :

In other words it does not recognize the json format.

I am using jquery for the ajax call. Any suggestions how to solve this?



Since you dont have access to the server where the API is hosted, you use can a web service utility like CURL to access the API. AJAX calls requires CORS (Cross Origin Resource Sharing) to be enabled on the server where the API is served.

You can call a web service on your local server page via AJAX from where the CURL call will be made and appropriate response returned.


There are several methods of bypassing cross-domain restrictions (CORS, JSONP, Iframe transport, etc.) but all methods have in common that the API server needs to corporate. So if you don’t have privileges on the API server, you cannot come across the cross-domain restrictions.

The only way to make this work would be putting a proxy in front of the API that you can control (the proxy could either live on the same domain or inject the appropriate CORS headers). However, this will affect performance and might also have legal implications.

Regarding JSONP, here’s an excellent explanation of how and why this works:

What is JSONP all about?


Recent Questions

Top Questions

Home Tags Terms of Service Privacy Policy DMCA Contact Us

©2020 All rights reserved.