I am trying to pass a json object that I have accessed from the database through a php file into JS using $.getJSON function. I am using the json_encode() function for this. The json object stored in the database is being retrieved. However, the array that I am obtaining in php ($arr) is not being accepted by the $.getJSON function.
Please Help. Thanks!
Sample code (php):
<?php
$arr = array();
while($row = mysqli_fetch_array($result)){
$attributes = $row['attributes'];
array_push($arr, $attributes);
}
$newArray = json_encode($arr);
echo $newArray;
?>
JS code:
var i, j;
var dataset = [];
for (i=0; i < 17; i++){
dataset[i] = [];
for (j=0; j < 17; j++){
dataset[i][j] = "";
}
}
$(document).ready(function(){
$.getJSON('getData.php', function(data) {
$.each(data, function(key, val) {
var x = val.posX,
y = val.posY;
});
});
});
The following is the output when I print $newArray.
[
"{\"position\":\"6.5\",\"posX\":6,\"posY\":5,\"type\":\"wall\"}",
"{\"position\":\"1.2\",\"posX\":1,\"posY\":2,\"type\":\"wall\"}",
"{\"position\":\"3.5\",\"posX\":3,\"posY\":5,\"type\":\"bee\",\"speed\":12}",
"{\"position\":\"7.3\",\"posX\":7,\"posY\":3,\"type\":\"bee\",\"speed\":12}",
"{\"position\":\"0.0\",\"posX\":0,\"posY\":0,\"type\":\"butterfly\",\"speed\":12,\"minspeed\":3.5,\"maxspeed\":12,\"speed_change_rate\":-0.9}",
"{\"position\":\"4.0\",\"posX\":4,\"posY\":0,\"type\":\"butterfly\",\"speed\":12,\"minspeed\":3.5,\"maxspeed\":12,\"speed_change_rate\":-0.9}"
]
$newArraydoesn't contain proper JSON