Fix escaping strings for JavaScript

The correct way to pass strings from PHP to JavaScript is json_encode.

Using addslashes or htmlspecialchars(..., ENT_QUOTES) may lead to
unexpected issues.
Declare some local variables

Let's avoid creating global variables
Merge pull request #1597 from mlocati/fix-javascript-strings

Fix escaping strings for JavaScript