1

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.

            $.ajax({
                type: "GET",
                url: url + query,
                contentType: "application/json",
                dataType: "jsonp",
                success: function(data){
                    console.log(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?

Alek
  • 57
  • 1
  • 6
  • I forgot to mention that I do not have privileges on the server so I can not change the header there. – Alek Jan 24 '15 at 10:48

2 Answers2

0

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.

Hemant
  • 1,999
  • 2
  • 12
  • 8
0

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?

Community
  • 1
  • 1
aaronk6
  • 2,701
  • 1
  • 19
  • 28