Francis Ngueukam
Francis Ngueukam

Reputation: 1024

Quote is breaking the syntax even after escape

I have a button who should call an action with 2 parameters (an integer and a String). I m using Yii2.

<button class="button_answer" 
    onclick="submitAnswer(
            <?php echo $id ?>, 
            <?php echo '\''.Html::encode($title).'\''?>
    );">
    Submit your answer
</button>  

it is working, but when the parameter title contains a single quote or a double quote, the syntax is broken.

I become something like this:

<button class="button_answer" onclick="submitAnswer(214, 'What's the ...?');">
     Post your answer
</button>

I dont know how to solve this.

Upvotes: 1

Views: 66

Answers (1)

Quentin
Quentin

Reputation: 944568

You need to encode the PHP string for JavaScript. Then you need to encode the JavaScript for HTML.

<?php
$js_string_title = json_encode($title);
$js = "submitAnswer($id, $js_string_title)";
$html_safe_js = htmlspecialchars($js);
?>

<button class="button_answer" 
     onclick="<?php echo $html_safe_js; ?>">
  Submit your answer
</button>  

A nicer approach would be to avoid inlining the JS altogether:

<button class="button_answer" 
        data-id="<?php echo htmlspecialchars($id); ?>"
        data-title="<?php echo htmlspecialchars($title); ?>">
     Post your answer
</button>

Along with something like:

addEventListener("click", answer_handler);

function answer_handler(event) {
     var el = event.target;
     if (el.classList.contains("button_answer")) {
         submitAnswer(el.dataset.id, el.dataset.title);
     }
}

Upvotes: 5

Related Questions