0

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?

4 Answers 4

1

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.

Sign up to request clarification or add additional context in comments.

2 Comments

And how do i import the PHP file into JS? and whats the correct code to replace 'data: [JSON]'?
@TonalDev Something like this: function(**data_from_php**) { if (Morris.EventEmitter) { dashboardMainChart = Morris.Area({//// data: **data_from_php**, ////}); } },
1

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.

Comments

1
// 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

5 Comments

here's the code, is there a problem in the syntax? initCharts: function(data_from_php) { $.get('/test.php', {}, function(result) { // Use Morris.Area instead of Morris.Line dashboardMainChart = Morris.Area({ data: result, }); }); } },
$.get('/test.php', {}, function(result) { // here in value result will be data from test.php }
try to add this code to page <script type="text/javascript" charset="utf-8"> $.get('url_for_test.php', {}, function(result) { alert(result); } </script>
Nothing basically happens..no alert, tried inserting this in the HTML file and in JS..ill try more tomorrow and come back here to report..thank you
0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.