NYCPHP Meetup

NYPHP.org

[nycphp-talk] Passing JavaScript arrays

Rob Marscher rmarscher at beaffinitive.com
Fri Jul 7 13:17:47 EDT 2006


If you're echoing a string from php into a javascript string var, you 
need to escape it.  Here's an example of what I'm talking about.  The 
escapeString function here is slightly modified from the one used in 
CakePHP's javascript helper:

<?php

function escapeString($string) {
   $escape = array("\r\n" => '\n', "\r" => '\n', "\n" => '\n', '"' => 
'\"', "'" => "\\'");
   return str_replace(array_keys($escape), array_values($escape), $string);
}

$string = "It's good to \"escape\" strings";

?>

<script language="javascript" type="text/javascript">
// <![CDATA[
   var string = '<?php echo escapeString($string); ?>';
   alert(string);
// ]]>
</script>




Cliff Hirsch wrote:
> And still use htmlentities if I am passing a string?
> 
> -----Original Message-----
> At 11:44 AM -0400 7/7/06, Cliff Hirsch wrote:
>> I need to pass data from PHP to JavaScript. Without resorting to any 
>> fancy Ajax's code, I currently build the JavaScript array variables
> using PHP echoes. Is this the best method? The arrays are visible in the
> HTML code. Any issues? For security, do I just escape the output like
> any other variable destined for the browser?
>> Regards,
>> Cliff
> 
> 
> Cliff:
> 
> To use a PHP variable in javascript, you create a javascript variable
> and then echo the value of the php variable. 
> 
> For example:
> 
> <?php
> 	$number = 100;
> ?>
> 
> <script language="javascript" type="text/javascript">
> 	var number = <?php echo $number; ?>;
> </script>
> 
> hth's
> 
> tedd
> 
> _______________________________________________
> New York PHP Community Talk Mailing List
> http://lists.nyphp.org/mailman/listinfo/talk
> New York PHP Conference and Expo 2006
> http://www.nyphpcon.com
> Show Your Participation in New York PHP
> http://www.nyphp.org/show_participation.php
> 



More information about the talk mailing list