How to escape string from PHP for javascript?
Asked Answered
V

4

26

lets imagine a form editor, it can edit available values. If the data contains " character (double quote) it "destroys" HTML code. I meant, lets check the code: so I generate HTML:

onclick="var a = prompt('New value: ', '<?php echo addslashes($rec[$i]); ?>'); if (a != null)....

and it results in

onclick="var a = prompt('New value: ', 'aaaa\"aaa'); if (a != null) { v....

and this makes JS work impossible, so that it ruins the code. With single qoute ' it works OK. mysql real escape does the same. How to escape any string so that it won't ruin javascript?


json_encode looked OK, but I must be doing something wrong, its still bad: heres a screenshot how Firefox sees it - it inserts a "bad" double quote! The value is just a simple number:

http://img402.imageshack.us/img402/5577/aaaahf.gif

and I did used:

('Ird be az új nevet:', <?php echo json_encode($rec['NAME']); ?>); if (a) { 
Verso answered 16/8, 2011 at 22:7 Comment(2)
possible duplicate of Pass a PHP string to a Javascript variable (including escaping newlines)Cherilyncherilynn
not exactly a duplicate, when its used inside an HTML attribute it requires an extra step of escapingLanlana
L
45

The value of the onclick attribute should be escaped like any other HTML attribute, using htmlspecialchars(). Actual Javascript strings inside the code should be encoded using json_encode(). For example:

<?php
$message = 'Some \' problematic \\ chars " ...';
$jscode = 'alert('.json_encode($message).');';
echo '<a onclick="' . htmlspecialchars($jscode) . '">Click me</a>';

That being said... onclick (or any other event) attributes are so 2005. Do yourself a favor and separate your javascript code from your html code, preferably to external file, and attach the events using DOM functions (or jQuery, which wraps it up nicely)

Lanlana answered 16/8, 2011 at 22:39 Comment(1)
Thanks for the typo fix, but I rejected it because I added the last paragraph after you edited it. I added your change manually.Lanlana
P
2

I'm really just re-wording what @Marshall House says here, but:

In HTML, a double quote (") will always end an attribute, regardless of a backslash - so it sees: onclick="var a = prompt('New value: ', 'aaaa\". The solution that @Marshall offers is to separate your code out into a function. This way you can print escaped PHP into it without a problem.

E.g.:

<script>
    // This is a function, wrapping your code to be called onclick.
    function doOnClickStuff() {
        // You should no longer need to escape your string. E.g.:
        //var a = prompt('new value:','<?php echo $rec[$i]; ?>');
        // Although the following could be safer
        var a = prompt('new value:',<?php json_encode($rec[$i]); ?>);
        if (a) { <!--javascript code--> }
        else { <!--javascript code--> }
    }
</script>
<someelement onclick="doOnClickStuff();"> <!-- this calls the javascript function doOnClickStuff, defined above -->
Puzzlement answered 16/8, 2011 at 22:35 Comment(1)
addslashes() doesn't always work as expected for encoding strings to javascript. json_encode() is much more reliable. Do note that it adds the quotes around the strings, so the value returned from json_encode() shouldn't be wrapped in another ''Lanlana
C
1
onclick="var a = prompt('New value: ', 'aaaa\"aaa'); if (a != null) { v....

Your problem is highlighted in bold. You can't quote a variable declaration you shouldn't need to escape the double quote once this is removed since it is within single quotes. Should look like this -

onclick="newFunc();"
<script>
function newFunc()  {
var a = prompt('New value: ', 'aaaa"aaa'); 
if (a != null) { v....
}
</script>
Chatwin answered 16/8, 2011 at 22:16 Comment(2)
I affraid I dont really understand. Ok, I wont use any escape, but its now onclick="var a = prompt('New value: ', 'áááá"áááá'); if (a != null) { spoiled againVerso
the only thing you should put in the onclick parameter is a call to a function that handles everything.. like thisChatwin
C
1
...onclick="new_func();"...
<script>
function new_func() {
    var a = prompt('new value:','<?php code; ?>');
    if (a) { <!--javascript code--> } else { <!--javascript code--> }
}
</script>
Chatwin answered 16/8, 2011 at 22:27 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.