Reputation: 21657
PHP
<?php
header('Content-type: application/json');
$return['ip'] = $_SERVER['REMOTE_ADDR'];
$results[] = array(
'ip' => $return['ip']
);
echo json_encode($results);
?>
jQuery
$.getJSON("http://domain.com/json/",
function(data){
console.log(data.ip);
});
});
But when I run the jQuery I've checked Fire bug and it says the following
GET http://domain.com/json/ 200 OK 81ms
And doesn't respond with the IP that I requested for. Have I missed something?
UPDATED CODE
PHP
<?php
header('Content-type: application/json');
$return['ip'] = $_SERVER['REMOTE_ADDR'];
$results = array(
'ip' => $return['ip']
);
echo json_encode($results);
?>
jQuery
$.getJSON("http://domain.com/json/", function(data){
console.log(data.ip);
});
Firebug Error
SyntaxError: invalid label {"ip":"XXX.XXX.XXX.X"}
An arrow points at the first quotation mark just before the word ip.
Upvotes: 1
Views: 330
Reputation: 548
You are returning:
[{'ip': 'XXX.XXX.XXX.XXX'}]
But you are treating it as if you are returning:
{'ip': 'XXX.XXX.XXX.XXX'}
You either need to change your JavaScript to console.log(data[0].ip)
or change your PHP to: $results = array( ... );
rather than $results[] = array( ... );
Either will fix your problem. :)
Upvotes: 5