0

I'm using this php code

echo " onclick='myFunction(" . $row['username'] . ")'"

that give me this result

onclick="myFunction(Francis88)"

But I want this:

onclick="myFunction('Francis88')"

How should I change my php code for obtain this?

GVillani82
  • 17,196
  • 30
  • 105
  • 172
  • Please, stop attaching event listeners in HTML. – tereško May 04 '13 at 17:22
  • Because you are mixing you HTML with you JavaScript. This ends up as an unmaintainable mess. [This](http://jsfiddle.net/teresko/KfBvt/) example should serve a simplified illustration of a better way. Google "event delegation" or "event bubbling" for more info. – tereško May 04 '13 at 17:25

2 Answers2

3

Use a \ to escape a character within a string, so for example:

echo " onclick=\"myFunction('" . $row['username'] . "')\""
Nick
  • 6,316
  • 2
  • 29
  • 47
2

I would use json_encode() for this to make sure it doesn't mess up with names such as O'Reilly; then, apply htmlspecialchars() to make sure the resulting string doesn't cause issues in HTML attributes:

printf(' onclick="myFunction(%s)"', 
    htmlspecialchars(json_encode($row['username']), ENT_QUOTES, 'UTF-8')
);

I'm also using single quotes here, so that the HTML attribute values can be enclosed in double quotes; arguable, but I hate single quoted attributes ;-)

See also my previous answer to find out the disadvantages of using inline JavaScript.

Community
  • 1
  • 1
Ja͢ck
  • 170,779
  • 38
  • 263
  • 309