Can't use PHP variable in JS

Just trying to get the result of query to the javascript array or something.

<head>
<script src="//ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script>
<title>Admin check</title>
<meta charset="UTF-8">
</head>

<body>
<script type='text/javascript'> 
<?php
include 'pdo_connect.php';
function pleaseWork() {
    return dataQuery("SELECT * FROM `grupy`")->fetchAll();
}

$work = pleaseWork();

echo "jArray = JSON.parse(<?php echo JSON_encode($work);?>);";
?>
</script>

Got code like that and there is the result:

<br />
<b>Notice</b>:  Array to string conversion in      <b>/virtual/chemioterapia2137.cba.pl/adminCheck.php</b> on line <b>20</b><br />
jArray = JSON.parse(<?php echo JSON_encode(Array);?>);  //jArray = JSON.parse('');

How can I get it working?

Upvotes: 0

Views: 982

Answers (2)

CodeGodie
CodeGodie

Reputation: 12142

A couple of errors:

  • Your code is very messy. Its easy to separate this. Try to place the most PHP outside of your JS.
  • When using json_encode it is already turning your array into a readable JS object. So no need for parsing.

Rewrite your code in this manner, I created the array result manually to mimic your DB results:

<?php

function pleaseWork()
{
    return array(
        array(
            "name" => "John",
            "age" => 52
        ),
        array(
            "name" => "Jane",
            "age" => 48
        )
    );
}

$work = pleaseWork();
$json = json_encode($work);
?>
<html>
    <head>
        <script src="//ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script>
        <title>Admin check</title>
        <meta charset="UTF-8">
    </head>
    <body>
        <script type='text/javascript'>
            var jArray = <?= $json ?>;
            console.log(jArray);
        </script>
    </body>
</html>

your browser's console result:

0: Object
  age: 52
  name: "John"

1: Object
  age: 48
  name: "Jane"

Upvotes: 3

user5653854
user5653854

Reputation:

Just change it to:

echo "var jArray = JSON.parse(". JSON_encode($work) .");";

Upvotes: 3

Related Questions