skip to Main Content
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.

2

Answers


  1. 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 = "FoonBar";
    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.

    Login or Signup to reply.
  2. 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>";
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search