String issue with adding dynamic HTML javascript

I use PHP to create a Javascript button that adds a checkbox and other HTML code.

What is the proper way to escape these characters in order to include them in the onclick event?

I saw that he suggested converting 'and' to ascii values, but that didn't seem to help.

$tempOutput = "<a href='temp.txt'>\"Happy\"</a>";
$tempOutput = str_replace("'", "&#39;", $tempOutput);
$tempOutput = str_replace('"', "&quot;", $tempOutput);

just leads to this if you echo the string right before use:

<a href=&#39;temp.txt&#39;>&quot;Happy&quot;</a>

and this if you check the page element:

<a onclick="
                    var divTag = document.createElement('div');
                    divTag.innerHTML = '&lt;a href='temp.txt'&gt;&quot;Happy&quot;&lt;/a&gt;';
                    document.getElementById('extraDiv').appendChild(divTag) ;
                ">test</a>

I also tried just adding innerHTML to extradiv, but could not succeed.

+3
source share
3 answers

I mainly use PHP rawurlencode () and Javascript unescape ():

  <?php
    $tempOutput = '<a href="temp.txt">'.htmlentities('"Happy"').'</a>';
  ?>
  <a onclick="
              var divTag = document.createElement('div');
              divTag.innerHTML = unescape('<?php echo rawurlencode($tempOutput);?>');
              document.getElementById('extraDiv').appendChild(divTag) ;
             ">test</a>
  <div id="extraDiv"></div>

This will also avoid errors with other characters, for example. line breaks.

+3

$tempOutput = str_replace(array("'",'"'), array("\'",'&quot;'), $tempOutput);
0

All Articles