NYCPHP Meetup

NYPHP.org

[nycphp-talk] A question about run php variable in javascript

John Campbell jcampbell1 at gmail.com
Thu May 1 12:18:20 EDT 2008


On Thu, May 1, 2008 at 11:59 AM, chad qian <nynj.tech at hotmail.com> wrote:
>
>  I need to run php to get street from mysql database.
> Then test the street variable in javascript
> if street is emty,javascript will pop up alert window
>
>  Here are my thoughts:
>
>  <?php
>  //connection to server,database
>
> $q = "select street from apt where username = '$user'";
> $result = mysql_query($q) or die(mysql_error());
> while($row = mysql_fetch_array($result)){
>   $street=$row['street'];
> }
> ?>
>  <script LANGUAGE="JavaScript">
> st=<?=$street?>;
> if(st)
>  alert("miss street");
>  </script>
>
>  Can I run st=<?=street?> in javascript?I'm not sure here.

Almost... that will produce the following:

st=123 abcd ave;

what you want is

var st = '123 abcd ave';
if(st === '') alert("miss street");

You also need to take care of escaping issues: what if the street name
is O'henry st?
then you would have
var st = '123 O'henry st'; // invalid javascript.

I  always use JSON to send data to javascript because it automatically
handles escaping and is much more flexible.  If you are not familiar
with JSON, it'll be worth your while to do a bit of reading.

Regards,
John Campbell



More information about the talk mailing list