We help IT Professionals succeed at work.

json_encode returns undefined values

Colin Brazier
on
Medium Priority
56 Views
Last Modified: 2020-03-13
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
Comment
Watch Question

CERTIFIED EXPERT
Most Valuable Expert 2017
Distinguished Expert 2019

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

Author

Commented:
Attached.  I didn't realise I could save it!
www.col-b.uk-1583941975923.log
Jim RiddlesPrepress/OMS Specialist
CERTIFIED EXPERT

Commented:
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

Jim RiddlesPrepress/OMS Specialist
CERTIFIED EXPERT

Commented:
Glad I could help.  Have a great day!
CERTIFIED EXPERT
Most Valuable Expert 2017
Distinguished Expert 2019

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

Author

Commented:
<?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

CERTIFIED EXPERT
Most Valuable Expert 2017
Distinguished Expert 2019

Commented:
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

Author

Commented:
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?
CERTIFIED EXPERT
Most Valuable Expert 2017
Distinguished Expert 2019
Commented:
Yup, that will do it - I think the JSON flag was only introduced in 1.4 (or thereabouts) but 1.3 is very old and should not be used.

The latest version of jQuery 1.x is 1.12.4 - if you are going to use version 1 then that is the version you should use.

The URL http://code.jquery.com/jquery.js loads version 11 - which should work however, version 1.x of jQuery is no longer maintained so you should be using version 3.x

The key thing here is - when the code does not do what you expect and you hack around it you are asking for trouble. Take the time to find out they why to save yourself headaches down the line.
Jim RiddlesPrepress/OMS Specialist
CERTIFIED EXPERT

Commented:
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.
CERTIFIED EXPERT
Most Valuable Expert 2017
Distinguished Expert 2019

Commented:
@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.