Search code examples
phpjqueryjsongetjson

$.getJSON not returning any data


I am trying to test $.getJSON() on localhost, but no data is returned.

Please correct me if I am wrong.

PHP:

$person['name'] = !empty($_GET['name']) ? $_GET['name'] : 'name';
$person['age'] = !empty($_GET['age']) ? $_GET['age'] : '00';

return json_encode($person);
?>

HTML / jQuery:

<script>
    $(document).ready(function(){
        $('.start').click(function(){
        $.getJSON('http://localhost/ewoe/server.php?name=natasha&age=22', alert(data.name));
        })
    }); //end ready
</script>

All files can be found in the same directory.
Although, the error I get after hitting the .start button is 'data not set'.


Solution

  • The problem is actually in the PHP output. The reason is that PHP, being a server-side language does not output to the HTML the stuff with return. If you want to print them out you have to echo them.

    Therefore return is not the answer, the answer is echo.

    Your php should be:

    <?php
    
    $person['name'] = !empty($_GET['name']) ? $_GET['name'] : 'name';
    $person['age'] = !empty($_GET['age']) ? $_GET['age'] : '00';
    
    echo json_encode($person);
    

    If you are getting errors on the No 'Access-Control-Allow-Origin' you should try giving a local path, not the full path:

    $.getJSON('server.php?name=natasha&age=22', ...);
    

    - NOTE

    Don't really know what you are doing there, but as a note, be carefull to possible manipulation of your script.

    By doing this, someone can see the source of your file and send request to the server.php by going to www.yoursite/ewoe/server.php?name=....

    Perhaps you should use the $_POST in the PHP and jQuery $.post requesting json format, like this:

    $.post('server.php', {name : 'natasha', age: 22}, function(response) {
        console.log(response.name)
    }, 'json');