nj51 nj51 - 4 months ago 16
jQuery Question

ajax JSON call returning array of strings instead of objects

When I do the ajax call I am parsing the json_encoded data and when I log the data to the console it's actually an array of strings instead of objects. It's showing this.

[
"{" todoText":"dgdgdfgdfgdf",
"completed":false,
"editable":false
}",

"{
"todoText":"test 2",
"completed":false,
"editable":false
}",

"{
"todoText":"test 3",
"completed":false,
"editable":false
}",

"{
"todoText":"sdfsdf",
"completed":false,
"editable":false
}"
]


This is the code I used to make the call to retrieve the data.

$(document).ready(function() {


$.get("php/listtasks.php", function(data){

var parsed = JSON.parse(data);


$('#directions').html(parsed[0]);

console.log(parsed);
})

});


This is the php code i used to encode the data and echo it back to the javascript.

$query = "SELECT * FROM list";
$result = $conn->query($query);
if (!$result) die ("Database access failed: " . $conn->error);

$rows = $result->num_rows;


for ($j = 0 ; $j < $rows ; ++$j)
{
$result->data_seek($j);
$row = $result->fetch_array(MYSQLI_NUM);


$x[$j] = $row[2];


}

echo json_encode($x);

Answer

Apparently, your $row[2] is a JSON object so you need to decode it like this:

$x[$j] = json_decode($row[2]);

I hope this will help you.