0

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);
2
  • have you tried: setting mimetype in php to json? and/or console.log(data) before/without JSON.parse? Commented Jul 19, 2016 at 23:44
  • @Jeff that outputs almost the same thing only now it has foward slashes throughout it Commented Jul 19, 2016 at 23:51

2 Answers 2

2

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.

Sign up to request clarification or add additional context in comments.

2 Comments

Thanks a lot, this works! I am just wondering if you can explain what happened. So first I stringifyed an object in javascript and sent an ajax request to send it to the server side.I then inserted this into a row in a mysql table. Why is that i have to decode that row just to encode it again to send it back?
$row[2] is a field, not row and is stored as a string (stringifyed object). I need to see your code in order to provide a detailed explanation !
0

Replace

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

With

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.