Seeking guidance from an expert on the following enigma.
In my HTML, I utilized getJSON()
.
When using a hardcoded array that can be json_encoded (by setting $DEBUG = true
), the data is passed to JavaScript for browser display successfully. However, encountering failure when attempting to generate dynamic array text from MySQL (by setting $DEBUG = false
).
I am puzzled on how to make the dynamically generated MySQL array work. Both scenarios can be tested with JSON formatted output in the browser at http://www.example.com/phpTWLLT/json_encoded_array.php.
If $DEBUG
is set to true
,
The output displayed in the browser from localhost/phpTWLLT/json_encode_array.php:
[{"active":"0","first_name":"Darian","last_name":"Brown","age":"28","email":"[email protected]"},{"active":"1","first_name":"John","last_name":"Doe","age":"47","email":"[email protected]"}]
The list will be shown in the browser as: 0, 1
If $DEBUG
is set to false
,
The output displayed in the browser from localhost/phpTWLLT/json_encode_array.php:
[{"active":"1"},{"active":"1"}]
The browser will show a blank display.
HTML file:
<!DOCTYPE html>
<html>
<head>
<script type='text/javascript' src='js/jquery.min.js'></script>
<meta charset="UTF-8">
</head>
<body>
<ul></ul>
<script type='text/javascript'>
$(document).ready(function () {
$.getJSON('json_encoded_array.php', function (data) {
$.each(data, function (key, val) {
$('ul').append('<li id="' + key + '">' + val.active + '</li>');
});
});
});
</script>
</body>
</html>
PHP script: json_encoded_array.php
<?php
$DEBUG = true;
if ($DEBUG) {
// Array data for debugging
} else {
// PHP script for querying MySQL database
}
echo json_encode($arr);
?>