简体   繁体   中英

Import data from Database to JS file

I am new to .js files and their use, I am trying to update charts that uses JS. What I need or trying to do is import information from my database to use it in my JS file to populate the chart. Here is the chart code and file name.

File Name charjs_custom.js

/*Polar chart*/
    var polarElem = document.getElementById("polarChart");

    var data3 = {
        datasets: [{
            data: [
                20,
                16,
                7,
                3,
                40
            ],
            backgroundColor: [
                "#7E81CB",
                "#1ABC9C",
                "#B8EDF0",
                "#B4C1D7",
                "#01C0C8"
            ],
            hoverBackgroundColor: [
                "#a1a4ec",
                "#2adab7",
                "#a7e7ea",
                "#a5b0c3",
                "#10e6ef"
            ],
            label: 'My dataset' // for legend
        }],
        labels: [
            "Blue",
            "Green",
            "Light Blue",
            "grey",
            "Sea Green"
        ]
    };

    new Chart(polarElem, {
        data: data3,
        type: 'polarArea',
        options: {
            elements: {
                arc: {
                    borderColor: ""
                }
            }
        }
    });

I need to alter the "data" and "label" sections using information from my DB, from what I have read I need to create a php file to retrieve the informationbut how do i convert it to JS and how do I tell it what information to use in the JS file. Also linking the "data" and "label" sections so the information will correspond to my tables

Tables I want to use is: make: id~count

File Name chart_test.php

<?php

//database
$host="my_host"; // Host name 
$username="my_username"; // Mysql username 
$password="my_password"; // Mysql password 
$db_name="my_database"; // Database name 

//get connection
$mysqli = new mysqli($host, $username, $password, $db_name);

if(!$mysqli){
    die("Connection failed: " . $mysqli->error);
}

//query to get data from the table
$query = sprintf("SELECT * FROM bureau GROUP BY make ");

//execute query
$result = $mysqli->query($query);

//close connection
$mysqli->close();

//now print the data
 print json_encode($data);

 ?>

you can interchange data between php backend and js frontend using JSON format. However i urge you to use nodejs as a backend service. it will integrate seamlessly with your js code.

Without really knowing anything about your data source, it would typically work like the following.

<?php
// Lets say your managed to convert your data from your database into something like.
$graph = [
    'data'       => [20, 16, 7, 3, 40],
    'background' => ['#7E81CB', '#1ABC9C', '#B8EDF0', '#B4C1D7', '#01C0C8'],
    'hover'      => ['#a1a4ec', '#2adab7', '#a7e7ea', '#a5b0c3', '#10e6ef'],
    'labels'     => ['Blue', 'Green', 'Light Blue', 'Grey', 'Sea Green']
];

?>

var polarElem = document.getElementById("polarChart");

var data3 = {
    datasets: [{
        data: <?php echo json_encode($graph['data']); ?>,
        backgroundColor: <?php echo json_encode($graph['background']); ?>,
        hoverBackgroundColor: <?php echo json_encode($graph['hover']); ?>,
        label: 'My dataset'
    }],
    labels: <?php echo json_encode($graph['labels']); ?>
};

So if I understand the mapping of the database, I would do:

<?php
//database
$host="my_host"; // Host name 
$username="my_username"; // Mysql username 
$password="my_password"; // Mysql password 
$db_name="my_database"; // Database name 

//get connection
$mysqli = new mysqli($host, $username, $password, $db_name);

if(!$mysqli){
    die("Connection failed: " . $mysqli->error);
}

//query to get data from the table
$query = sprintf("SELECT * FROM bureau GROUP BY make ");

//execute query
$result = $mysqli->query($query);


// Define configuration array
$config = array(
   'datasets' => array(
        array(
            'data' => array(),
            'backgroundColor' => array(), // This could be statically loaded, or dynamic if the DB has colors
            'hoverBackgroundColor' => array(), // This could be statically loaded, or dynamic if the DB has colors
            'label' => 'My Dataset'
        )
    ),
    'labels' => array()
);

// Loop through database result and add
while($row=mysqli_fetch_assoc($result)){
    array_push($config['labels'], $row['make']); // Add label
    array_push($config['datasets'][0]['data'], $row['totalValue']); // Add value
}

//close connection
$mysqli->close();

//now print the data
echo json_encode($config);

What you ultimately do with that config depends on how you're loading this chart. It could be an AJAX request that you would then use the result of in place of data3 such as:

$.get( "chart_test.php", function( data ) {
    new Chart(polarElem, {
        data: data,
        type: 'polarArea',
        options: {
            elements: {
                arc: {
                    borderColor: ""
                }
            }
        }
    });
}, "json" );

Or embedded into a php file so that instead of printing the json_encode($config); you would create the entire script:

new Chart(polarElem, {
        data: <?= json_encode($config) ?>,
        type: 'polarArea',
        options: {
            elements: {
                arc: {
                    borderColor: ""
                }
            }
        }
    });

It all depends on the setup you have thus far.

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