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."'";
}
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>';
'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
json_encode()
isn't available?Call to undefined function json_encode()
. PHP v. 5.2.9. OK, it seems that it would work withoutjson_encode()
- testing 2012-04-05 18:16