0

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?

2 Answers2

3

Just change it to:

echo "var jArray = JSON.parse(". JSON_encode($work) .");";
  • 1
    Damn I was so close, I tried to do echo "jArray = JSON.parse(. JSON_encode($work) .);"; – stevenhawkingsbiggestfan Feb 16 '16 at 15:29
  • `Uncaught SyntaxError: Unexpected token o` pointing on `[object Object],[object Object]` – stevenhawkingsbiggestfan Feb 16 '16 at 15:32
  • What is your code now? I think now its a problem with your js: http://stackoverflow.com/questions/8081701/i-keep-getting-uncaught-syntaxerror-unexpected-token-o –  Feb 16 '16 at 15:34
  • When I get rid of JSON_parse it throws `Notice: Array to string conversion jArray = . JSON_encode(Array) .; ` I just added this attribute to connection `$dbh->setAttribute(PDO::ATTR_DEFAULT_FETCH_MODE, PDO::FETCH_ASSOC);` and changed echo `echo "jArray = . JSON_encode($work) .;";`. – stevenhawkingsbiggestfan Feb 16 '16 at 15:40
3

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"
CodeGodie
  • 12,116
  • 6
  • 37
  • 66