0

I am dynamically creating an anchor that calls a javascript function. It works with one string parameter but not with two. I believe I am not escaping the quotes around the parameters correctly. In search for an answer I came across the following

onclick="alert('<?echo $row['username']?>')"  

and the next one I found left me completely baffled

echo('<button type="button" id="button'.$ctr.'"onClick="showMapsInfo(\''.str_replace("'", "\\'", $maps_name).'\', \''.str_replace("'", "\\'", $ctr).'\');"><img src="img/maps_logo.gif"></button><br/>');

If someone would please

  1. Explain why the single quotes around username do not have to be escaped?

  2. Where there is a "dummies" write up on escaping characters so I could try to decipher the second example.

1
  • instead of str_replace, use addslashes and provide a blank space here: '"onClick Commented Jul 7, 2012 at 6:15

5 Answers 5

1

Let's examine your first example

onclick="alert('<?echo $row['username']?>')" 

The important part here is, that everything outside of <? … ?> is pure HTML and never looked at by the PHP interpreter. Therefore, the only part that is relevant for PHP is the code inside <? … ?>, namely echo $row['username']. Here, one does not need to do any escaping.

Your second example, in contrast

echo('<button type="button" id="button'.$ctr.'"onClick="showMapsInfo(\''.str_replace("'", "\\'", $maps_name).'\', \''.str_replace("'", "\\'", $ctr).'\');"><img src="img/maps_logo.gif"></button><br/>');

is written purely in PHP, no surrounding HTML. Therefore, you have to be careful with the quotes. Let's build this up from scratch to see what happens here. When you build something like this, you would probably start with

echo('<button type="button" id="button1" onClick="showMapsInfo(\'...\');"><img src="img/maps_logo.gif"></button><br/>');

Because the single quotes were already used as string delimiters, they must be escaped inside the string with \'. Now for the part inside the javascript function. Put even simpler, the above code boils down to

echo('showMapsInfo(\'...\');');

which results in

showMapsInfo('...');

when we want to insert some dynamic parts instead of the '...' part, we need to end the string with ' and concatenate it back together with .. Suppose you wanted to insert a variable $foobar in there, then you would write:

echo('showMapsInfo(\''.$foobar.'\');');

which results in

showMapsInfo('<VALUE OF $foobar>');

Your example does not insert $foobar into this string, but rather the following expression:

str_replace("'", "\\'", $maps_name).'\', \''.str_replace("'", "\\'", $ctr)

Which uses str_replace in order to again escape the content, but with a little twist: It is not escaped for PHP, but for the resulting Javascript! Every single quote ' becomes an escaped single quote \' in the output, but you need to write \\' because the backslash needs to be escaped itself, in order to produce a backslash as output.

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

1 Comment

Thank you for such a detailed reply it has helped considerably.
1

You can replace the quotes and then use heredoc, it is more legible and easier to understand.

$maps_name = str_replace("'", "\\'", $maps_name);
$ctr       = str_replace("'", "\\'", $ctr);

echo <<<HTML

<button type="button" id="button$ctr" onClick="showMapsInfo('$maps_name', '$ctr');"><img src="img/maps_logo.gif"></button><br/>

HTML;

4 Comments

Edited to fix the php.net link to the English version. This is surely more readable, but still requires escaping the ' inside the php vars otherwise the JS will throw a syntax error.
@FabrícioMatté, Thanks, i forgot to update the link. About the ', he can just call str_replace() before echo the heredoc, i've made an update.
@FabrícioMatté, Thanks! (Valeu! Primeiro brasileiro que encontro por aqui!)
There are many Brazilians here (even though you don't see them very often), well don't forget to check out the Stack Overflow in Portuguese proposal and commit if you didn't already. :P
0

You could use json_encode function for the javascript variable.

echo sprintf(
  '<button type="button" id="button%s" onClick="showMapsInfo(%s, %s);">
   <img src="img/maps_logo.gif"></button><br/>',
    htmlspecialchars($ctr), json_encode($maps_name), json_encode($ctr));

1 Comment

Thank you for answering but for now json will have to wait I am still struggling with PHP, javascript, CSS and HTML5.
0

I think you dont have problem in escaping single quote as the function is working when you are

calling it using one parameter only.

Check if you are creating the whole parameter sting correctly, if the comma is added properly and in javascript if single quote comes around bot the parameters.

finally the parameter string should look like

'param1', 'param2'

Comments

0
  1. The single quotes around username do not have to be escaped because it is part of the PHP variable, not the JavaScript.

  2. Information on injecting PHP variables into JavaScript can be found here and more info here.

    You only need to enclose the PHP variables in quotes if the variable is a string.

1 Comment

Thank you for your help, I will follow the links.

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.