使用MySql数据填充JavaScript数组

I've looked through various other questions on SO, but can't quite get the right answer. Basically, I have an array that needs data from a MySql database. Here's what I've tried:

var $name = "Foo",
    $x = 10,
    $bar =
      <? php
        $barQuery = mysql_query("SELECT item FROM table WHERE name = '$name' AND number = '$x'");
        $barArray = array();

        while ($r = mysql_fetch_assoc($barQuery))
        {
          $barArray[] = $r['item'];
        }

        echo json_encode($barArray);
      ?>;

EDIT: I then post this to a .php file, and print the returned data:

$.post("file.php", {bar: JSON.stringify($bar), name: $name}).done(function(data)
{
  $('body').html(data);
  window.print();
  setTimeout("location.reload(true)", 500);
});

However, I get an error saying "syntax error, unexpected T_VARIABLE". Is it not possible to populate a JS array this way, or is there another way to do it?

var $name = "Foo",
    $x = 10,
    $bar = "
      <?php
        $barQuery = mysql_query("SELECT item FROM table WHERE name = '$name' AND number = '$x'");
        $barArray = array();

        while ($r = mysql_fetch_assoc($barQuery))
        {
          $barArray[] = $r['item'];
        }

        echo json_encode($barArray);
      ?>";

You have a superfluous space inside the PHP opening tag:

      <? php
        ^--- this shouldn't be there

As it stands, the <? is parsed as a short open tag, and so the php is parsed as a(n undefined) constant, which is immediately followed by $barQuery—hence the syntax error that you see: unexpected T_VARIABLE.