Skip to content
Advertisement

How to echo php string with special characters inside javascript function parameter

I have a button on my website that triggers an onclick event with the following function

onclick="
updatePage('<?php echo $page['title']; ?>','<?php echo $page['id']; ?>','<?php echo $page['attachedfiles']; ?>','<?php echo $page['attachmentprefix']; ?>');
"

this usually works fine but if the $page[‘title’] contains a single quote it breaks the rest for example if the string was “What’s your name?” it would break after the “what ‘”

Is there a fix for this, i have tried using echo htmlspecialchars($page['title']) but it doesnt work. I am still a beginner so i am not too sure on how to solve this.

I am sorry if this is a duplicate question but from other solutions ive seen this seems like more of a javascript issue rather than php

Advertisement

Answer

You can try the addslashes function. Example:

<div class="thediv"></div>

<?php
    $title = "This isn't the title";
?>

<script>

    var div = document.querySelector('.thediv');

    div.innerHTML = '<?= addslashes($title) ?>';

</script>
User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement