0
echo "<button onClick='follow(".$name.");'></button>";

I need to pass a string as a parameter in follow(user) function onClick event jquery. But it's getting called as a value.

I tried kind of everything, but in php it looks a bit of a big deal for me. Is there any other way around to get the expected result as a string from a php variable.

fedefomin
  • 19
  • 3
  • 1
    Best way to fix it: [remove the inline handler](https://stackoverflow.com/a/59539045), attach the listener properly using JavaScript instead – CertainPerformance Sep 20 '20 at 19:50
  • You need to quote that string. As mentioned, using inline onclick functions is not the most modern approach – charlietfl Sep 20 '20 at 20:09
  • Please specify what you are attempting to do. Are you wanting to do some PHP operation on click? If so you need to use AJAX! – SJacks Sep 20 '20 at 20:25

2 Answers2

0

Quotes are off and if you're passing a string you need quotes wrapping the string in the function call.

There is various ways to do it, for standard " in html properties:

echo '<button onClick="follow(\''.$name.'\')"></button>';

echo "<button onClick=\"follow('".$name."')\"></button>";

echo "<button onClick=\"follow('$name')\"></button>";

for single quotes

echo '<button onClick=\'follow("'.$name.'")\'></button>';

echo "<button onClick='follow(\"".$name."\")'></button>";

echo "<button onClick='follow(\"$name\")'></button>";

But that's presuming your users are nice, a crafty user may create a username with \n in it, then from POSTing to storing and retrieving it would most likely be rendered as a new line:

<?php
$name = "Foo\nBar";
echo '<button onClick="follow(\''.$name.'\')"></button>'; 

Rendering the following which would cause the page to break:

<button onClick="follow('Foo
Bar')"></button>

Or worse a username like:

$name = "Foo')\"></button>\n<button onClick=\"window.location.href = ('http://example.com";

Which would render a stored XSS:

<button onClick="follow('Foo')"></button>
<button onClick="window.location.href = ('http://example.com')"></button>

So a better solution then to directly pass it in, would be to escape it, using htmlentities and json_encode so \n is not rendered by the html.

echo '<button onClick=\'follow('.json_encode(htmlentities($name, ENT_QUOTES, 'UTF-8')).')\'></button>';

Which would render to:

<button onClick='follow("Foo&#039;)&quot;&gt;&lt;\/button&gt;\n&lt;button onClick=&quot;window.location.href = (&#039;http:\/\/example.com")'></button>

Though you should be validating usernames on create before allowing such an attack.

marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
Lawrence Cherone
  • 46,049
  • 7
  • 62
  • 106
0

You echo a php variable in javascript without adding quotes thus ending with a javascript variable name instead of a string.

Just add escaped quotes like this:

echo "<button onClick='follow(\"".$name."\");'></button>";
rallisf1
  • 17
  • 7