3

There is something wrong with the way I am printing MySQL and the javascript is not executing it. Here is an example.

square[1] = "asdfasdfadsf";

When I print "asdfasdfadsf" from my MySQL database, the javascript does not work. However, if I simply type "asdfasdfadsf" in the static HTML it executes fine. I have tried as many PHP functions and charset conversions as I can. Please Help!

1
  • Is that the actual output you're getting? Are you sure you're not forgetting to quote the value on the output? Commented May 22, 2012 at 17:58

2 Answers 2

5

I suggest the json_encode PHP function. Apart from properly printing the string, it also escapes all dangerous characters.

square[1] = <?php echo json_encode($my_string); ?>;
Sign up to request clarification or add additional context in comments.

1 Comment

json_encode() worked! It was because I was breaking the line in the string.
3

You need to add quotes around the string from the database.

// Add quotes around the call which prints the vale from PHP.
// this turns it into a JavaScript string.
square[1] = '<?php echo "asdfasdfadsf"; ?>';
//----------^^----------------------------^^

// Or...
square[1] = '<?php echo $row["value_from_your_db"]; ?>';

Note: json_encode() is recommended if this is anything more than a simple string that may have internal quotes of its own requiring additional escaping.

1 Comment

The quotes are correct. The strings will look alike when viewing the source.

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.