0

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?

3
  • It is literally impossible to day. Why don't you console.log(data) before calling JSON.parse() on it. Commented Feb 7, 2013 at 21:30
  • 2
    What is data? And do you really output tons of script tags? Commented Feb 7, 2013 at 21:31
  • 1
    You don't need JSON.parse here. Echoing JSON from PHP into JavaScript will just create an object literal in JavaScript. Commented Feb 7, 2013 at 21:33

3 Answers 3

2

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.

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

2 Comments

Ok. great! But how can i use it as a json string? could you make an example of how to escape the quotes? I don't know how to do that.
It would look like 'var obj = JSON.parse( "'.addslashes(json_encode($row)).'");'
0

You need the field name of the table.

json_encode($row['fieldname'])

Comments

0

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);
}

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.