I'm having trouble getting javascript data from a json.
To better explain, the data comes from the database, like this:
// PHP
$rs = mysqli_query($con, "SELECT id_acao as id, text FROM acoes");
$data = array();
if (mysqli_num_rows($rs) > 0) {
while($row = mysqli_fetch_assoc($rs)){
$data[] = $row;
}
}
echo json_encode($data);
This is returning the following (as a string):
bla bla bla "}, {" id ":" 9 "," text ":" bla bla bla "}]
That is, it returns a list and not a JsonString. In the page that receives I can not convert it to access the data ..
So:
var data = JSON.parse(ajax.responseText[0]);
or so (as I saw in some forums the use of [] .concat)
var data = JSON.parse(([].concat(ajax.responseText))[0]);
gives the same error.
Uncaught SyntaxError: Unexpected token in JSON at position 0 at JSON.parse ()
I was only able to convert it to an object by doing this:
var data = [].concat(JSON.parse(JSON.stringify(ajax.responseText)));
But when you try to access it with
var valor = data[0];
or even with
var valor = data[0]['text'];
I'm returning a type (string) with all the content of ajax !!
What am I forgetting or doing wrong? Thank you to anyone who can help me! At
UPDATE: I was testing inserting the value directly into JSON.parse
instead of using a variable.
Amazingly, if I type exactly what is in ajax.responseText
works. If you copy and paste the contents, through the console.log, it gives an error.
// typed, works fine
var data = JSON.parse('[{"id":"1","text":"Windows XP"},{"id":"9","text":"não concluído"}]');
// copied and pasted from console.log(ajax.responseText);
, gives error
var data = JSON.parse('[{"id":"1","text":"Windows XP"},{"id":"9","text":"não concluído"}]');
I'm finding that some special invisible character is in the middle of the string of ajax.responseText
.
I have tested both codes above, my last two quotes, and worked out both.