Search code examples
javascriptjqueryajaxcross-site

How to get data from cross-site? I'm using $.post


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.


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();
    ?>