Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 655
Robin Carlo Catacutan Avatar asked Oct 09 '22 06:10

Robin Carlo Catacutan


1 Answers

Use the jQuery.getJSON method instead of .get, if you want your JSON to be parsed. Also, make sure that the jQuery library is correctly loaded.

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

Currently, you're using $.get(url, function(data){...}). In this context, data is a string containing the response from the server:

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

Using alert(data) inside the function will show this string.

like image 52
Rob W Avatar answered Oct 13 '22 10:10

Rob W