Abhraneel Sarma
Abhraneel Sarma

Reputation: 23

Pass JSON object from database to JS using $.getJSON

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}"
]

Upvotes: 1

Views: 1053

Answers (2)

Quentin
Quentin

Reputation: 943142

The basic problem here is that you are storing JSON in the database instead of having a database designed to hold the data you are dealing with.

i.e. Your database table should have columns for position, posX, etc.

Consequently, when you return the data to the browser you are returning a JSON array of strings where each string is a JSON text in its own right.

To deal with that, you will have to parse each string as you loop over them.

    $.each(data, function(key, val) {
        val = JSON.parse(val);
        var x = val.posX,

A better approach would be to decode each string on the server before you return it.

The best approach would be to normalise your database so you have data you can actually query.

Upvotes: 2

Gary Liu
Gary Liu

Reputation: 13918

try to use echo stripslashes($newArray); after json_encode

Upvotes: -1

Related Questions