Question

I'm testing a javascript code which is on localhost. This file requires data from a remote server in JSON format. When I directly hit the JSON url, I get the data, but in javascript, I'm getting empty response.

What might be the reason? I'm using jquery post method to get the data.

Was it helpful?

Solution

As others have said, you cannot use AJAX to access a remote server. You have to use JSONP. If you don't have control of the other server, or if the other server doesn't offer JSONP, you have to use a proxy.

It's really easy to write one in PHP. http://www.betavine.net/bvportal/blog/view.html?blogId=101&postId=ff8080811afe49d3011afe4bb5de0003

<?
ob_start();

$url = $_REQUEST['url'];
$curl_handle = curl_init($url);
curl_setopt($curl_handle, CURLOPT_HEADER, 0);
curl_setopt($curl_handle, CURLOPT_FOLLOWLOCATION, 1);
curl_setopt($curl_handle, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($curl_handle, CURLOPT_USERAGENT, "Owen's AJAX Proxy");

$content = curl_exec($curl_handle);
$content_type = curl_getinfo($curl_handle, CURLINFO_CONTENT_TYPE);
curl_close($curl_handle);
header("Content-Type: $content_type");
echo $content;
ob_flush();
?>

OTHER TIPS

You cannot access any resource from different domain using JavaScript due to security reasons. jQuery cannot do anything for this but there are some ways to achieve this like JSONP or YQL.

Take a look at this quick tip for cross domain AJAX request with YQL.

http://net.tutsplus.com/tutorials/javascript-ajax/quick-tip-cross-domain-ajax-request-with-yql-and-jquery/

$.post is an ajax method, and you can't use ajax methods to access data from a different origin.

See the jQuery docs for details:

Due to browser security restrictions, most "Ajax" requests are subject to the same origin policy; the request can not successfully retrieve data from a different domain, subdomain, or protocol.

There's a protective measure set up with JavaScript that you should look into. It's the same origin policy. Basically it means if you want to do an XmlHttpRequest for data from a server that isn't of the same origin that the page you are on, you can't, unless you jump through hoops.

Check out JSON-P, or jQuery's methods for overcoming this.

The server you are requesting from must either support JSONP or CORS.

Otherwise, it is not possible.

It is also not possible to make a JSONP request using POST, it must be GET

Requesting data from a different domain is restricted as a security concern (see CORS), specifically to prevent XSS(cross site scripting) attacks.

You can try a couple of alternatives:

  • JSONP is an option if the other domain supports it
  • here's another relevant question

You can use YQL to request resources from another domain.

Apart from these alternatives you can always make a server proxy and have that proxy query the domain and return results.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top