I have a PHP script that runs an SQL query. I'd like to put the results in an array, encode it as a JSON object, echo it back to the Javascript that called it, and use it as an array to write some HTML.
This is the JS which calls the PHP script using POST. I attempt to parse the echoed data using JSON.parse(data)
(I also tried jQuery.parseJSON(data)
- not sure if there's a difference), and I display the raw echoed data on the HTML page for testing.
var components = []; // create empty array for component list
if ($('#area').val) { // if area contains a value and isn't zero (i.e. an area has been selected)
$.post("/basic/get_area_components.php"
,{area: $("#area").val()}
,function(data){ components = JSON.parse(data);
$("#components_raw").html(data);
$("#components").html(components);
});
}
The PHP script (after the database connection has been set up) looks like this:
$result = $conn->query("SELECT Component FROM ConfigComponent WHERE Parent =" . $area);
while($row = $result->fetch_array()) {
$rows[] = $row;
}
$i = 1;
foreach ($rows as $value) {
$components[$i] = $value[0];
$i++;
}
echo json_encode($components);
When I run the script, I get the raw output on the HTML page as follows:
{"1":"Handlebar","2":"Stem","3":"Headset","4":"Fork"}
which appears to be a correctly formatted JSON object, but nothing from the parsed components
array, and no exceptions. I have tried scanning the array using forEach
and printing or alerting the elements individually, to no avail.
How can I parse the JSON object correctly and use it in the Javascript? Is it a problem with the JS parsing, or the PHP encoding?