1

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.

ngplayground
  • 20,365
  • 36
  • 94
  • 173
  • If you're accessing JSON on a different domain, [you probably need to use JSON-P instead](http://stackoverflow.com/q/2681466/901048). AJAX requests can normally only go to the same domain as the page making the request. – Blazemonger Feb 05 '13 at 16:08
  • isn't the field called 'id'? – David Fregoli Feb 05 '13 at 16:10
  • Look at the [answer to this question](http://stackoverflow.com/questions/2822609/invalid-label-firebug-error-with-jquery-getjson). – mccannf Feb 05 '13 at 17:01

1 Answers1

5

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. :)

Dan
  • 550
  • 3
  • 7
  • im getting SyntaxError: invalid label pointing to the "ip" of the return – ngplayground Feb 05 '13 at 16:18
  • Please can you update your question with the code you're now using, and the *exact* error message it is giving you in response? – Dan Feb 05 '13 at 16:27