1

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

1 Answer 1

4

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>';
Sign up to request clarification or add additional context in comments.

4 Comments

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().
Updated answer with an alternative function
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.
You should only be escaping $type!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.