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?
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?
Use a \
to escape a character within a string, so for example:
echo " onclick=\"myFunction('" . $row['username'] . "')\""
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.