testing
testing

Reputation: 20279

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

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."'";
}

Upvotes: 1

Views: 412

Answers (1)

Cal
Cal

Reputation: 7157

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>';

Upvotes: 4

Related Questions