Note that there are some explanatory texts on larger screens.

plurals
  1. POencoding a PHP variable with quotes and line breaks to be passed to a Javascript function (and then reverse the encoding)
    text
    copied!<p>Say you have a PHP variable called $description with the following value (that contains quotes and line breaks):</p> <pre><code>Tromp L'oeil Sheath Dress You will certainly "trick the eye" of many in this gorgeous illusion. Add it to your fall wardrobe before it disappears. </code></pre> <p>You want to pass the contents of this variable into a Javascript function that writes that value into an INPUT of type text.</p> <p>How would you do this? I tried this:</p> <pre><code>$description = htmlspecialchars ( $product-&gt;description, ENT_QUOTES ); </code></pre> <p>However, I get a JS error. I also tried this:</p> <pre><code>$description = rawurlencode ( $product-&gt;description ); </code></pre> <p>This encodes the value like so:</p> <pre><code>Michael%20Kors%0A%0ATromp%20L%27oeil%20Sheath%20Dress%0A%0AYou%20will%20certainly%20%22trick%20the%20ey%22%20of%20many%20in%20this%20gorgeous%20illusion.%20Add%20it%20to%20your%20fall%20wardrobe%20before%20it%20disappears.%0A%0AAvailable%20in%20Black%2FNude </code></pre> <p>This value can be passed as a JS variable, but I don't know of a JS function that will cleanly reverse a PHP rawurlencode.</p> <p>Is there a matching pair of functions that I could use to encode a variable in PHP to allow it to be passed into a JS function -- and then reverse the encoding in JS so that I get the original value of the PHP variable?</p> <p>EDIT: To clarify the question and reply to comments, here is some test code:</p> <pre><code>&lt;?php $str =&lt;&lt;&lt;EOT Tromp L'oeil Sheath Dress You will certainly "trick the eye" of many in this gorgeous illusion. Add it to your fall wardrobe before it disappears. EOT; echo 'here is the string: &lt;pre&gt;' . $str . '&lt;/pre&gt;'; ?&gt; &lt;script type="text/javascript"&gt; &lt;?php // this does not work with JS as i get an unterminated string literal if i just use addslashes in the following commented-out line // echo 'alert(\'' . addslashes($str) . '\');'; // this works with JS (the alert activates) but how do i un-rawurlencode in JS? // echo 'alert(\'' . rawurlencode($str) . '\');'; // this does not work with JS, because of the line breaks echo 'alert(\'' . htmlspecialchars ($str, ENT_QUOTES) . '\');'; ?&gt; &lt;/script&gt; </code></pre>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload