简体   繁体   中英

Passing php array for use in javascript using json_encode

I know this has been asked plenty of times before but still I have a problem after readaing all the other posts on the subject... Somewhere between my php code -and the javascript it is sitting in- my array is going awol.

In the attached code, I have an echo for debugging of the php. When I cut out the php section from the javascript and run it separately with the echo on, it shows me that it is building my json_encoded array correctly.

In the javascript immediately after the php end I assign the php to a javascript variable, so I can use it for further processing (plotting a graph). Putting in display statements, to display the content of the result of the php call to get the array into javascript, shows the array is empty.

If I cut and paste the output of the php echo and assign this literal to the javascript chartData array then everything works fine. Why is the javascript not getting the php array content?

Here's the code snip:

<script>
...some java script stuff;
<?php
// Define the mySQL db connection
$db = new PDO('mysql:host=localhost;dbname=remets;charset=UTF-8', 'remets', 'remets',         array(PDO::ATTR_EMULATE_PREPARES => false, PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION));
// Define SQL query to fetch data from mySQL
$stmt = $db->query("SELECT WeekNumber,XAxisCategory,YAxisValue FROM Metric WHERE ReportID = 'Q3' ORDER BY WeekNumber,XAxisCategory ASC");

                                // declarations
                                $amData = array();
                                $amArray = array();
                                $ctrinner = 0;
                                $ctrouter = -1;
                                $prevweek = "9999";

                                // Fetch data from mySQL and put it in an array in the format we need
                                while($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
                                    if ($prevweek !== $row['WeekNumber']) {
                                        $ctrouter++;
                                        $ctrinner = 0;
                                        $amData[$ctrouter]["week"] = "".$row['WeekNumber'];  // Prepending (or appending) the empty string makes the json encoding think the week number is a string, which is MUST have for AmCharts
                                  }
                                    $ctrinner++;
                                    $amData[$ctrouter][$row['XAxisCategory']] = $row['YAxisValue'];
                                    $prevweek = $row['WeekNumber'];
                                }

                                    // Using json_encode puts the data into an array format that we can use in a javascript
                                    $amJSONArray = json_encode($amData);

                                    // Echo is for debugging only.
                                    // echo $amJSONArray;


                            ?>

                            var chartData = <?php echo $amJSONArray; 
?>;

...more javascript stuff;

</script>

@Mahdi: The output of the print_r is: Array ( [0] => Array ( [week] => 1301 [Accepted] => 30 [Failed] => 5 [Passed] => 20 [Planned] => 5 [Skipped] => 5 [Unknown] => 26 ) [1] => Array ( [week] => 1302 [Accepted] => 25 [Failed] => 2 [Passed] => 25 [Planned] => 2 [Skipped] => 3 [Unknown] => 20 ) [2] => Array ( [week] => 1303 [Accepted] => 26 [Failed] => 26 [Passed] => 29 [Planned] => 26 [Skipped] => 26 [Unknown] => 10 ) )

@Mahdi: This is the jscript code immediately after the php (It is commented out because I tried lots of different options that were recommended in other posts in this forum and others - none of them work. I can run the php code and that works fine. If I copy the output of the echo in the php code snip I posted earlier and simply assign that to chartData (ie: chartData = ""; my chart is produced fine. The problem is not with the charting tool but somehow the array content is just not visible to the javascript which is directly below it in the .js file. Thanks for your time up til now.

                            //var chartData = "<?php print($amJSONArray); ?>";  // This just returns the literal in the speech marks
                            //var chartData = '<?php print($amJSONArray); ?>';  // This also returns the literal in the speech marks
                            //var chartData = "<?php echo($amJSONArray); ?>";   // This just returns the literal in the speech marks
                            //var chartData = '<?php echo($amJSONArray); ?>';   // This also returns the literal in the speech marks
                            //var chartData = <?php echo ($amJSONArray) ?>;     // This returns empty
                            //var chartData = <?php echo $amJSONArray ?>;       // This returns empty
                            //var chartData = (<?php echo $amJSONArray ?>);     // This returns empty
                            //alert(chartData);                                                                 // Returns empty - just showing the contents of the array if I do the json_encode within the php part
                            //alert(<?php echo $amJSONArray ?>);                                // Returns empty - just showing the contents of the array if I do the json_encode during the array fetch

UPDATE: I think there's something fundamentally wrong going on at my side. I used a very simple example which should write "hello world" to the screen but it returns nothing at all. If I substitute the 'write' with an 'alert' then it still shows nothing in the alert popup. Does anyone know why this would not be working? The code is:

<?php
   $testvar = "Hello World";
?>
<html>
<head>
<script type="text/javascript">
function hello()
 {
   // create JavaScript variable, fill it with Php variable
   var testvar = "<? print $testvar; ?>";
  // output to screen

   document.write( testvar );   
 } 
</script>
</head>

<!-- Call JavaScript function to display variable -->
<body onload="hello()" >
</body>
</html>  

如果您能够以字符串形式访问数据,则可以尝试使用内置的JSON.parse()将其转换为可用的javascript。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM