Reputation: 1293
I have written a code which sends a query to mysql database and then gets the results row by row using $row = mysql_fetch_assoc($result).
I need to send the data for each row to a javascript function.
Here is the piece of code I used:
while($row = mysql_fetch_assoc($result))
{
echo '<script type="text/javascript">'.'queryResults('. json_encode($row) . ');'.'</script>';
}
In my javascript function I have :
function queryResults(data){
var results = JSON.parse(data);}
However, I get error:
"SyntaxError: JSON.parse: unexpected character"
Where is the problem with my code?
Upvotes: 0
Views: 111
Reputation: 664207
JSON directly inside a script tag is interpreted as a JavaScript object literal - you actually pass an object to the queryResults
function. To use JSON.parse()
(which you don't have to) you would need to wrap it inside JavaScript string delimiters and escape all quotes in the string returned by json_encode
, so that JavaScript would see a valid string.
Btw, your sample function is missing the data
parameter in its signature.
Upvotes: 2
Reputation: 2099
I think the problem is that you have no parameter specified in the function signature. This may solve the issue:
function queryResults(data){
var results = JSON.parse(data);
}
Upvotes: 0
Reputation: 5399
You need the field name of the table.
json_encode($row['fieldname'])
Upvotes: 0