TonalDev
TonalDev

Reputation: 583

JSON from php into JS file

I'm trying to draw DB tables using php PDO which i successfully made using the following code:

test.php

<?php
$dbh = new PDO("mysql:host=localhost;dbname=test", "root", "");
$statement=$dbh->prepare("SELECT * FROM pdotable");
$statement->execute();
$results=$statement->fetchAll(PDO::FETCH_ASSOC);
$json=json_encode($results);

echo $json;

?>

I need to take the results into a chart JS code which his data array is in this code:

  initCharts: function() {
        if (Morris.EventEmitter) {
            // Use Morris.Area instead of Morris.Line
            dashboardMainChart = Morris.Area({
                element: 'sales_statistics',
                padding: 0,
                behaveLikeLine: false,
                gridEnabled: false,
                gridLineColor: false,
                axes: false,
                fillOpacity: 1,

                data: 

                 [{
                    period: '2011',
                    sales: 1400,
                    profit: 400
                }, {
                    period: '2011 Q2',
                    sales: 1100,
                    profit: 600
                }, {
                    period: '2011 Q3',
                    sales: 1600,
                    profit: 500
                }, {
                    period: '2011 Q4',
                    sales: 1200,
                    profit: 400
                }, {
                    period: '2012 Q1',
                    sales: 1550,
                    profit: 5
                }],


                lineColors: ['#399a8c', '#92e9dc'],
                xkey: 'period',
                ykeys: ['sales', 'profit'],
                labels: ['Sales', 'Profit'],
                pointSize: 0,
                lineWidth: 0,
                hideHover: 'auto',
                resize: true
            });

        }
    },

How do i replace the data : [json] with the JSON from the PHP result?

Upvotes: 0

Views: 112

Answers (4)

Danila Ganchar
Danila Ganchar

Reputation: 11223

// test.php
$dbh = new PDO("mysql:host=localhost;dbname=test", "root", "");
$statement=$dbh->prepare("SELECT * FROM pdotable");
$statement->execute();
$results=$statement->fetchAll(PDO::FETCH_ASSOC);
$json=json_encode($results);

header('Content-type: application/json');

echo $json;

//js
...
if (Morris.EventEmitter) {
    //if you use jQuery
    $.get('/test.php', {}, function(result) { //or use $.getJSON
        dashboardMainChart = Morris.Area({
            ...
            data: result,
            ...

xmlhttp if you not use jQuery

Upvotes: 1

huchister
huchister

Reputation: 27

You would need to echo out the content type, so that browser sees return data and accept as json.

echo ('Content-type: application/json');
$json = json_encode($results); 
echo $json;

I usually open up the google console, or firefox's firebug to see the response tab on the network tab you've sent to. From there, you can see what data you are getting back from server to check if you are echoing right data or not.

Furthermore, you can print them in console log by pluggin

console.log(data); 

Within your javascript to confirm whether you are getting data in right format.

You might as well look upon some db document to pull out data just what you need.

Instead of SELECT * FROM pdotable, SELECT period, sales, profit would do.

Hope this helps.

Upvotes: 1

ZI TEG
ZI TEG

Reputation: 63

In php file after closing tag you need write JS part, like it

<script type="text/javascript" charset="utf-8">
var data = <?php echo json_encode($results); ?>;
</script>

Be careful with the semicolon. Just need to correct a little JS script, but I think you can do it.

Upvotes: 1

ciro
ciro

Reputation: 801

you only need this json_encode function

this accept an array as parameter and return a string json that you can insert inside a js code simple use echo function

the js code must insert in php file and not in external js

Upvotes: 0

Related Questions