7

Say you have a PHP variable called $description with the following value (that contains quotes and line breaks):

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.

You want to pass the contents of this variable into a Javascript function that writes that value into an INPUT of type text.

How would you do this? I tried this:

$description = htmlspecialchars ( $product->description, ENT_QUOTES );

However, I get a JS error. I also tried this:

$description = rawurlencode ( $product->description );

This encodes the value like so:

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

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.

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?

EDIT: To clarify the question and reply to comments, here is some test code:

<?php
$str =<<<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: <pre>' . $str . '</pre>';
?>

<script type="text/javascript">
<?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) . '\');';
?>
</script>
bobbyh
  • 643
  • 3
  • 9
  • 16
  • Why not just echo the actual variable into a JavaScript variable? All you need to worry about is the single and/or double quotes, which can easily be fixed with `addslashes()`... – animuson Jul 13 '10 at 18:10
  • What method are you getting this into js from PHP? Is it just echoed into script tags assigning js variables and executing somewhere in the post-output html? – DeaconDesperado Jul 13 '10 at 18:10
  • Can you be more specific on what "doesn't work" with htmlspecialchars ? – Savageman Jul 13 '10 at 18:11
  • Thanks for the fast comments, I added some sample code so you can see my question more clearly... – bobbyh Jul 13 '10 at 18:33
  • possible duplicate of: http://stackoverflow.com/questions/168214/pass-a-php-string-to-a-javascript-variable-including-escaping-newlines – Scott Evernden Jul 13 '10 at 18:37

6 Answers6

3

simplest would be to use json_encode()

ceejayoz
  • 176,543
  • 40
  • 303
  • 368
Scott Evernden
  • 39,136
  • 15
  • 78
  • 84
2

I ran into problems using some of the answers proposed here, including issues with line breaks and decoding certain html entitites like /. I ended up using rawurlencode (in PHP) and decodeURIComponent (in Javascript) as matching functions to encode/decode the string so it could be passed as a JS variable. Here is working code for anybody else running into this problem.

<?php
$str =<<<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.
Available in Black/Nude
EOT;
echo 'here is the string: <pre>' . $str . '</pre>';
?>
<p>below is the variable doc.write'd after being rawurlencod'ed in PHP then decodeURIComponent'ed in JS:</p>
<script type="text/javascript">
<?php
echo 'document.write(decodeURIComponent("'. rawurlencode($str).'"));';
?>
bobbyh
  • 643
  • 3
  • 9
  • 16
1

You can use json_encode if available. It encodes the string according to the JSON data format that is a subset of JavaScript; so any JSON is also valid JavaScript.

<script type="text/javascript">
<?php
    echo 'alert('. json_encode($str).');';
?>
</script>

Otherwise try PHP’s rawurlencode and decode it with JavaScript’s decodeURI:

<script type="text/javascript">
<?php
    echo 'alert(decodeURI("'. rawurlencode($str).'"));';
?>
</script>
Gumbo
  • 643,351
  • 109
  • 780
  • 844
  • Thanks, just to follow up, decodeURI almost works, but doesn't decode certain characters like /, so I went with decodeURIComponent, as you can see in my answer... – bobbyh Jul 14 '10 at 19:31
0

Json is the solution. See sample code Two pages to demonstrate

First Page json.php

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<title>Untitled Document</title>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script>
</head>

<body>


<script type="text/javascript">
  $(document).ready(function() {
    // This is more like it!
    $('#submit').live('click', function() {
        var id=$("#id").attr("value");
        $.getJSON("json-call.php", {id:id}, function callback(data) {
            $("#list").html("var1:"+data['var1']+"<br/>"+"var2:"+data['var2']+"<br />id:"+data['id']);
        });
    });

  });
</script>

<input id="id" type="text" value="test value" />
<input type="button" id="submit" value="submit" />

<div id="list"></div>


</body>
</html>

Second Page json-call.php

$var1 = 'your name';
$var2 = 'your address';
$id = $_REQUEST['id'];
print(json_encode(array ('var1' => $var1, 'var2' => $var2, 'id'=>$id)));

and Results

var1:your name
var2:your address
id:test value
Developer
  • 25,073
  • 20
  • 81
  • 128
0

Not sure whether json_decode does everything you need. htmlspecialchars() and htmlspecialchars_decode() should do the trick for everything but the line breaks. The line breaks are kind of a pain, since the combination of linebreaks and carriage returns will depend on the browser, but I think something like this should work:

$value = "your string with quotes and newlines in it.";

//take cares of quotes
$js_value = htmlspecialchars($value);    
//first line replaces an ASCII newline with a JavaScript newline
$js_value = str_replace("\n",'\n',$js_value);
//second line replaces an ASCII carriage return with nothing, so you don't get duplicates
$js_value = str_replace("\r",'',$js_value);

//reverse to convert it back to PHP
$php_value = str_replace('\n',"\r\n",$js_value);  
$php_value = htmlspecialchars_decode($php_value);

Maybe not the most elegant solution, but that's not really my specialty. ;) Also, keep in mind that newline characters will just end up like spaces in an <input type="text"> field.

NChase
  • 1,638
  • 4
  • 22
  • 25
0

Here is a litle something I have made:

function safefor_js($str) {
    return str_replace(array("'",'"',"\n"), array('\x22','\x27','\\n'), $str);
}
  • What about the backslash character? – Gumbo Jul 13 '10 at 20:56
  • I didn't think of that, but I don't think it is needed. I just tested it with things like: "a\na", "a\x22a", "a\xn\x22a", "a\x27a" (all with out the quotes) and it did not break the page in any way. Is there something I'm missing? If I'm wrong I definitely would want to fix it. – Echo says Reinstate Monica Jul 13 '10 at 21:08