tags:

views:

233

answers:

6

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>
+1  A: 

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
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
+2  A: 

simplest would be to use json_encode()

Scott Evernden
A: 

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"&gt;
<html xmlns="http://www.w3.org/1999/xhtml"&gt;
<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"&gt;&lt;/script&gt;
</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
Ghost
A: 

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
A: 

Here is a litle something I have made:

function safefor_js($str) {
    return str_replace(array("'",'"',"\n"), array('\x22','\x27','\\n'), $str);
}
Echo
What about the backslash character?
Gumbo
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
+1  A: 

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