Avatar of Colin Brazier
Colin Brazier
Flag for United Kingdom of Great Britain and Northern Ireland asked on

json_encode returns undefined values

Why am I getting values Undefined in this page?

http://www.col-b.uk/json/

It is using json_encode.

I am debugging via the console and the array seems fine but individual values are undefined - see screen grab js.jpg.

Here's the code of script.js
$(document).ready(function(){
    $.ajax({
        url: 'ajaxfile.php',
        type: 'get',
        dataType: 'JSON',
        success: function(response){
			
            var len = response.length;
				
            for(var i=0; i<3; i++){
                var id = response[i].id;
                var username = response[i].username;
                var name = response[i].name;
                var email = response[i].email;
				
				console.log(response);
				
				console.log(response[i].username);

                var tr_str = "<tr>" +
                    "<td align='center'>" + (i+1) + "</td>" +
                    "<td align='center'>" + username + "</td>" +
                    "<td align='center'>" + name + "</td>" +
                    "<td align='center'>" + email + "</td>" +
                    "</tr>";

                $("#userTable tbody").append(tr_str);
            }

        }
    });
});

[embed=file 1446456]

Open in new window

js.jpg
JavaScriptPHPJSON

Avatar of undefined
Last Comment
Julian Hansen

8/22/2022 - Mon
Julian Hansen

what does console.log(response) show when placed on line 7

Update:
(Hint: instead of a screen grab post the actual json data from the console. It makes testing that much easier)
Colin Brazier

ASKER
Attached.  I didn't realise I could save it!
www.col-b.uk-1583941975923.log
Jim Riddles

It doesn't look like you are parsing your JSON request.  Try the following code:
$(document).ready(function(){
    $.ajax({
        url: 'ajaxfile.php',
        type: 'get',
        dataType: 'JSON',
        success: function(response){
            records = JSON.parse(response);
            for(var i=0; i<3; i++){
                var id = records[i].id;
                var username = records[i].username;
                var name = records[i].name;
                var email = records[i].email;
				
				console.log(records);
				
				console.log(records[i].username);

                var tr_str = "<tr>" +
                    "<td align='center'>" + (i+1) + "</td>" +
                    "<td align='center'>" + username + "</td>" +
                    "<td align='center'>" + name + "</td>" +
                    "<td align='center'>" + email + "</td>" +
                    "</tr>";

                $("#userTable tbody").append(tr_str);
            }

        }
    });
});

Open in new window

Your help has saved me hundreds of hours of internet surfing.
fblack61
Jim Riddles

Glad I could help.  Have a great day!
Julian Hansen

 records = JSON.parse(response);

Open in new window

This should not be necessary when you have the dataType set to 'JSON'.

This is why I asked for the data dump because something is not right.

I am guessing on your server you have double encoded your JSON - but putting a JSON.parse inside a handler that is part of $.ajax with dataType = 'JSON' is just glossing over the problem.

What are you using to generate the response - what does your server code look like?

Having looked at your log it is definitely a case of double encoding. Your response is dumping as text JSON which means that whatever is sending the JSON is encoding it twice.

The tut was correct - the code is correct on the client - the problem is the server code. Can you show us that.
Colin Brazier

ASKER
<?php
// connect to the database
require_once("../includes/initialise.php");
$dbi = new fobg_database_i();

$return_arr = array();

$query = "SELECT id, username, name, email FROM users ORDER BY name";

$result = mysqli_query($dbi->dbLink,$query);

while($row = mysqli_fetch_array($result)){
    $id = $row['id'];
    $username = $row['username'];
    $name = $row['name'];
    $email = $row['email'];

    $return_arr[] = array("id" => $id,
                    "username" => $username,
                    "name" => $name,
                    "email" => $email);
}


// Encoding array in JSON format
echo json_encode($return_arr);

Open in new window

⚡ FREE TRIAL OFFER
Try out a week of full access for free.
Find out why thousands trust the EE community with their toughest problems.
Julian Hansen

That looks correct - somewhere your code is not doing what it should.

I have put up a sample demonstrating (with your code) that it works without the JSON.parse. The code also gives an alternative way to build a table in JavaScript

You can see the sample here
Colin Brazier

ASKER
The problem with the original code was the version of jquery used...

      <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js"></script>

is wrong.  This one works:

        <script src="http://code.jquery.com/jquery.js"></script>

So I should always use the latter?
ASKER CERTIFIED SOLUTION
Julian Hansen

THIS SOLUTION ONLY AVAILABLE TO MEMBERS.
View this solution by signing up for a free trial.
Members can start a 7-Day free trial and enjoy unlimited access to the platform.
See Pricing Options
Start Free Trial
GET A PERSONALIZED SOLUTION
Ask your own question & get feedback from real experts
Find out why thousands trust the EE community with their toughest problems.
Jim Riddles

Did my solution not solve the issue?  I agree that the OP should be using the latest version of jQuery, but that shouldn't invalidate my solution.  That is just my opinion, no need to respond.
This is the best money I have ever spent. I cannot not tell you how many times these folks have saved my bacon. I learn so much from the contributors.
rwheeler23
Julian Hansen

@Jim,

The problem with the solution you offered is that it distracted from a bigger underlying problem. If the requirement was to remain on jQuery 1.3 then yes your solution would have been bang on.

However the asker stated that this code was from a tut where there was a claim it was correct. A tut implies a learning situation and to go the route you did while not exploring why the teaching example did not work - left a a big hole that needed to be filled.

The solution clearly made use of the JSON flag - it was therefore intended that the automatic parsing of JSON should be used - this in turn implies that the right version of jQuery needs to be used.

By following the thread of "Why" it was not working as intended it allowed us to get to the actual cause of the problem. If we had just gone with the JSON.parse() it could have opened up a whole bunch of issues down the line where other code (also assuming that 1.4+ was in play) would stop working.