0
I’m having trouble getting the javascript data from a json.
To better explain, the data comes from the database, thus:
//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 me the following (as a string) :
[{"id":"1","text":"bla bla bla"},{"id":"9","text":"bla bla bla bla"}]
That is, it returns a list and not a Jsonstring. On the page you receive I cannot convert it to access the data..
Thus:
var data = JSON.parse(ajax.responseText[0]);
or so (as I have seen in some forums the use of []. Concat)
var data = JSON.parse(([].concat(ajax.responseText))[0]);
makes the same mistake.
Uncaught Syntaxerror: Unexpected token in JSON at position 0 at JSON.parse (<Anonymous>)
All I could do was convert it to an object:
var data = [].concat(JSON.parse(JSON.stringify(ajax.responseText)));
But when trying to access it with
var valor = data[0];
or even with
var valor = data[0]['text'];
is returning me a type (string) with all ajax content!!
What am I forgetting or doing wrong? Thank you to anyone who can help me! At
UPDATE: was testing by entering the value directly into JSON.parse
instead of using a variable.
Oddly enough, if I type in exactly what’s in ajax.responseText
works. If I copy and paste the content, by the console.log, gives error.
// typed , it works
var data = JSON.parse('[{"id":"1","text":"Windows XP"},{"id":"9","text":"não concluído"}]');
// copied and pasted from console.log(ajax.responseText);
, makes a mistake
var data = JSON.parse('[{"id":"1","text":"Windows XP"},{"id":"9","text":"não concluído"}]');
I’m thinking it’s some special, invisible character that’s in the middle of the string ajax.responseText
.
I tested both codes above, my last two quotes, and it worked both.
What’s in
ajax.responseText
only?– Guilherme Lautert
As above, ajax.responseText there is a type (string) with all content, exactly the same as my first quote above in yellow.
– ThiagoYB
The request was made from Jquery or normal javascript?
– Isac
@Thiagoyb then his problem is precisely in
JSON.parse(ajax.responseText[0]);
that should only beJSON.parse(ajax.responseText);
– Guilherme Lautert
So when do I
var data = JSON.parse(ajax.responseText)
, error occurs exactly as above.– ThiagoYB