Pass a string into a Javascript function all in PHP - How to escape correctly?

Go To StackoverFlow.com

0

I have the following code:

echo '
    <td>    
        <input type="button" name="delete" value="X" onclick="clearSelection(this.form, '.$type.');this.form.submit();" />
    </td>'
;

The problem is that I cannot pass a string to the clearSelection() Javascript function, because $type needs to be in parentheses.

I tried it with backslash, u0222, multiple quotes and so on but nothing brought me to the solution.

Solution:

$type = json_escape_string($type);
$raw_text = "clearSelection(this.form, $type); this.form.submit();";
$escaped_text = htmlspecialchars($raw_text);
echo '<td><input type="button" name="delete" value="X" onclick="'.$escaped_text.'" /></td>';

function json_escape_string($str){
    $str = strtr($str, array('\\'=>'\\\\',"'"=>"\\'",'"'=>'\\"',"\r"=>'\\r',"\n"=>'\\n','</'=>'<\/'));
    return "'".$str."'";
}
2012-04-05 18:10
by testing


3

You need to escape it first:

$escaped_text = HtmlSpecialChars(json_encode($raw_text));

json_encode() turns it into a valid JS string, then HtmlSpecialChars() escapes it for use within an HTML attribute.

If you have an old version of PHP without json_encode(), use this instead:

$escaped_text = HtmlSpecialChars(json_escape_string($raw_text));

function json_escape_string($str){
    $str = strtr($str, array('\\'=>'\\\\',"'"=>"\\'",'"'=>'\\"',"\r"=>'\\r',"\n"=>'\\n','</'=>'<\/'));
    return "'".$str."'";
}

For your particular variables:

$escaped_type = HtmlSpecialChars(json_escape_string($type));
echo '<td><input type="button" name="delete" value="X" onclick="clearSelection(this.form, '.$escaped_type.'); this.form.submit();" /></td>';
2012-04-05 18:11
by Cal
What is if json_encode() isn't available? Call to undefined function json_encode(). PHP v. 5.2.9. OK, it seems that it would work without json_encode() - testing 2012-04-05 18:16
Updated answer with an alternative functio - Cal 2012-04-05 18:20
If I use your function I get 'clearSelection(this.form, \'products\'); this.form.submit();' in the onclick attribute (onlick=""). And that doesn't seem to work - testing 2012-04-05 18:28
You should only be escaping $type - Cal 2012-04-05 18:35
OK, you are right - testing 2012-04-06 07:19
Ads