Escape single quote when a Javascript function call is rendered from PHP
I have many instances where I need to call a JavaScript function from a PHP generated html code. For example,
I tried several different approach to solve this issue but the best and the simplest solution that I found was to simply escape the single quote from PHP since the data is already being rendered from PHP code.
So the above code should be updated to:
So I created utility helper method as follows:
I'm sure there may be better way to solve this issue but I couldn't get it to work using PHP's
Let me know if you find a better way to solve this issue. Thanks.
<a href="javascript: updateTitle('<?php echo $current_title;?>');">Update</a>
<script>
function updateTitle(title)
{
var new_title = prompt('update title', title);
}
</script>
This works pretty well except if the $current_title
variable contains a single quote, then it will result in javascript syntax error and the link will not work.I tried several different approach to solve this issue but the best and the simplest solution that I found was to simply escape the single quote from PHP since the data is already being rendered from PHP code.
So the above code should be updated to:
<a href="javascript: updateTitle('<?php echo str_replace("'", "\\'", $current_title);?>');">Update</a>
However, if the $current_title
variable contains a double quote then it will also result in syntax error but replacing the double quote with escaped double quote like above does not work in this case. For double quote, you will have to replace it with "
. So I created utility helper method as follows:
// HandyUtils class
public static function escapeQuotes($string)
{
$string = str_replace("'", "\\'", $string);
$string = str_replace("\"", """, $string);
return $string;
}
And the final code can be written as
<a href="javascript: updateTitle('<?php echo HandyUtils::escapeQuotes($current_title);?>');">Update</a>
I'm sure there may be better way to solve this issue but I couldn't get it to work using PHP's
addslashes()
or htmlspecialchars()
functions...Let me know if you find a better way to solve this issue. Thanks.
Leave a comment
If you sign up and log in:
OK, Sign me up!
However, there are times when unintended content is converted to emoticon because the content happens to have one of the emoticon symbols. That's why it's always good idea to preview your comment before posting and when you see this type of problem, you can indicate NOT to auto convert.