1

I have a php-code, which can get json data from RPC server.

<?php
error_reporting(E_ALL);

$server = 'http://pogoda.ngs.ru/json/';
// API-method
$method = 'getForecast';
// input data
$params = array('name' => 'current',
        'city' => 'nsk');

// 
$request = array('method' => $method,
         'params' => $params);

// encode to json
$request = json_encode($request);


// 
$opts = array('http' => array('method'  => "POST",
                  'content' => $request)); 

// context stream
$context = stream_context_create($opts);

// get result
$result = file_get_contents($server, 0, $context);
$result = json_decode($result, true);

print_r($result);
?>

and then i try to do this in javascript by jquery. I found a lot of ways, but none of them has worked.

<html>
<head>
    <link rel=stylesheet type="text/css" href="myCssFile.css"> 
    <script type="text/javascript" src="jquery-1.11.0.min.js"></script>
</head>
<body>
<?php
header('Content-type: text/html; charset=utf-8');
?>

<script>
    var url = "http://pogoda.ngs.ru/json/";

    var request = {};
    request.method = "getForecast";
    request.params = {};
    request.params.name = "current";
    request.params.city = "nsk";
    request.params.jsonrpc = "2";
    request.params.dataType = "json";

    $.ajax({
    url: url,
    data: JSON.stringify(request),
    type: "POST",
    contentType: "application/json"
    }).done(function(rpcRes) {
    alert("ok");
    }).fail(function(err, status, thrown) {
    alert("Error ajax");
    });

</script>
</body>
</html>

I got errors or nothing all the time. Does anybody know something about it?

Sergey
  • 140
  • 9
  • 1
    Your code is fundamentally impossible - you cannot use AJAX calls to make calls to arbitrary servers. JS AJAX can only talk to the server from which the JS code was loaded in the first place. Check your browser's error console and you'll see the security warnings/errors. – Marc B Feb 22 '14 at 21:54
  • Here is another question that dealt with the same problem: http://stackoverflow.com/questions/2851164/making-an-ajax-request-to-another-server – bentrm Feb 22 '14 at 22:01

1 Answers1

1

Marc B's comment is close, but not quite correct. You cannot make arbitrary AJAX requests to servers you do not control. Security policies prevent this.

If you control both endpoints, you can add an Access-Control-Allow-Origin header to allow another domain to make requests to it, but if you don't, you're out of luck.

Your best bet would likely be to keep using a PHP script that gets the data, and call that script with AJAX if you need it to live-update in a page - that way you use your own server as a sort of proxy, allowing it to work.

Collin Grady
  • 2,226
  • 1
  • 14
  • 14