Gawet
Gawet

Reputation: 315

Does Javascript methods auto-escape quotes?

I want to know if javascript methods auto-escape quotes, because this code work:

Example #1

<?php $foo ="hey a quote ' "; ?>
<input type="text" value="<?php echo $foo; ?>" id="foo" />
<script>
    bar = document.getElementById('foo').value;
    alert(bar+'there is a quote, will it work? ,');
</script>

It displays the alert fine, but this one:

Example #2

<?php $foo ="hey a quote ' "; ?>
<button onclick="alert('<?php echo $foo; ?>');">test</button>

...doesn't. Obviously, it's because the quote isn't escaped with a \.

But then again, neither is it in the first example, so why is that so ? Does javascript's method auto-escape quote when it picked stuff from DOM ?

Or is it just the value() method maybe ?

I've found nothing, so if you have even the beginning of an answer, I''ll be glad.

Upvotes: 1

Views: 795

Answers (2)

trincot
trincot

Reputation: 350961

The difference is really that in the first code example, the quote appears in a context where there are no wrapping single quotes, so there is no ambiguity. If you would have wrapped the HTML attribute values with single quotes (which is valid HTML also), you'd have a problem:

<?php $foo ="hey a quote ' "; ?>
<input type='text' value='<?php echo $foo; ?>' id='foo' />

In that case the single quote should have been escaped as an HTML entity: &apos;:

<?php $foo ="hey a quote &apos; "; ?>
<input type='text' value='<?php echo $foo; ?>' id='foo' />

Now in the second code example you provided, the single quote will appear in wrapped single quotes (for the string literal passed to alert). This is an issue, because the single quote will now end the string literal, and the characters following it will lead to a syntax error.

Here the quote appears in a JavaScript string literal (the alert code), not as in the HTML context of the first example. In JavaScript string literals, single quotes can be escaped with the backslash.

So in both cases (HTML or JavaScript) you could need a form of escaping. They are different.

Note that none of this is related to PHP.

Upvotes: 0

Robin Zigmond
Robin Zigmond

Reputation: 18249

PHP is processed on the server, producing HTML (including embedded javascript in this case). This happens before the HTML is sent to the browser to interpret, including any JS.

You will see if you inspect the generated HTML source, that your second example becomes:

<button onclick="alert('hey a quote ' ');">test</button>

which isn't valid JS syntax.

Your first version works basically because you do not have an extraneous single quote in the code your PHP string is inserted into. The insertion instead produces:

<input type="text" value="hey a quote ' " id="foo" />

which is perfectly fine. And that value is then passed on to the alert call in the JS.

Upvotes: 1

Related Questions