Json_encode return undefined

My script returns undefined value from my json_encode php

index.php

<?php
    $returnThis['user'] = "Robin098";
    $returnThis['id'] = "08465";

    echo json_encode($returnThis);
?>

sample.html

<head>
    <script>
        function clickHere(){
            $.get("index.php", function(data) {
            alert(data.user);
            });
        }

    </script>
</head>
       <body>
       <input type="button" onclick = "clickHere();" value="ClickHere!"/> 
       </body>

How can i fix this?

+5
source share
2 answers

Use jQuery.getJSONinstead .getif you want your JSON to be parsed. Also, make sure the jQuery library is loaded correctly.

    function clickHere(){
        $.getJSON("index.php", function(data) {
            alert(data.user);
        });
    }

You are currently using $.get(url, function(data){...}). In this context data, this is the line containing the response from the server:

{"user":"Robin098","id":"80465"}

Using alert(data)inside the function, you will see this line.

+3
source

It looks like you are tuning $returnThis, but then returning $aReturn. You do not want:

$returnThis['user'] = "Robin098";
$returnThis['id'] = "08465";

echo json_encode($returnThis); 
+1

All Articles