0

I wanted to make my chart script an external file but I never used ajax before and would like some help on how it works, my chart and everything works fine linked to a database, I just wanted to make the js file external.

Here is the php code:

    <?php 

        //delcare and run sql
        $sql = "SELECT prices, generations from products";
        $result = mysqli_query($con, $sql);

        //variables
        $dataX = "";
        $dataY = "";

        //Loop to get the data
        While($row=mysqli_fetch_assoc($result)){
            $dataX = $dataX."'".$row['generations']."',";
            $dataY = $dataY."'".$row['prices']."',";
        }

        //Trim your string for white spaces and for comma at the end
        $dataX=trim($dataX,",");
        $dataY=trim($dataY,",");

    ?>

And here is the javascript code:

        <script type="text/javascript">

        var myChart = document.getElementById('myChart').getContext('2d');

var data = {
    type: 'bar', //bar, horizontablbar, pie, doughnut, radar, polararea
    data: {

        labels: [ <?php echo $dataX?> ],
        datasets: [{
            label: 'product sales',
            data: [ <?php echo $dataY ?> ],
            backgroundColor: [,'tomato', 'green','blue','cyan'],borderWidth: 1,
            borderColour: 'grey', hoverBorderColor: 'black'
            }],
    },
    options: {
        title: {
            display: true,
            text: 'Product Sales Report'
        },
        legend: {
            display: false,
        },

    scales: {
        yAxes: [{
            display: true,
            ticks: {
                beginAtZero: true,
                steps: 10,
                stepValue: 5,

            }
        }]
    }
    }
}

var Chart = new Chart(myChart, data);

</script>

2 Answers 2

1

You need to create a file that serves a JSON response (for example) of your data, then access it using XHR request (or easily, use jQuery's AJAX) to render the data on your chart.

Using the code you provided, you should create another PHP file that prints the a JSON response:

<?php
$sql = "SELECT prices, generations from products";
$result = mysqli_query($con, $sql);

//variables
$dataX = array();
$dataY = array();

//Loop to get the data
while($row = mysqli_fetch_assoc($result)){
    array_push($dataX, $row['generations'];
    array_push($dataY, $row['prices'];
}

header('Content-Type: application/json');
echo json_encode(array(
    "dataX" => $dataX,
    "dataY" => $dataY
));

Let's assume you called this file data.php and placed it on the root directory. You now need to access the file using a jQuery AJAX request and render your chart using this data:

$.ajax({
    url: '/data.php',
    method: 'GET',
    success: function(response) {
        var dataX = response.dataX;
        var dataY = response.dataY;

        renderHtmlChart(dataX, dataY);
    }
});

Hope you can find the right way to create the renderHtmlChart function :)

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

9 Comments

Hi, thanks for your help, this is where I have got now with the chart.js file and sort of struggling what to do if you can help, I have created the data.php file but unsure on the js file thanks - pastebin.com/FGdbPPHg
Still no luck, could it be because i am searching data from a submit button? Here is my full code if you could take a look - pastebin.com/wauj4MgS
First of all, please include the jQuery library in your HTML file as the first script, then the Chart.js file as second the your local file as the third file. Then please add this piece of code into your local JavaScript file: pastebin.com/8zX4jgrq
What do you mean by third script local file and also once I done the changes I keep getting that the 'Uncaught TypeError: Chart is not a constructor' pastebin.com/CZkL3Qpp
Please switch between lines 8 and 9 and add this line right after the opening of the head tag: <script src="https://code.jquery.com/jquery-3.4.1.min.js" integrity="sha256-CSXorXvZcTkaix6Yvo6HppcZGetbYMGWSFlBw8HfCJo=" crossorigin="anonymous"></script>
|
0

Managed to fix the issues was a simple variable name that wasn't correct to display the chart.

Index.php file

<html>
<?php
include "connection.php";
?>
    <head>

    </head>
    <body>
    <div id="navigation">
        <div id="nava">
        <a href="">Home</a></li>
        <a href="">News</a></li>
        <a href="">Contact</a></li>
        <a href="">About</a></li>
        </div>
    </div>
        <form method="get"> 
        <select name="year" size="1" >
            <option value="2014">2014</option>
            <option value="2015">2015</option>
            <option value="2016">2016</option>
        </select>
    <input type="submit"></input>
    </form> 

        <canvas id="myChart"></canvas>

<script src="https://code.jquery.com/jquery-3.4.1.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.9.3/Chart.min.js"></script>
<script type="text/javascript" src="chart.js"></script>

<script type="text/javascript" src="styles.js"></script>
    </body>
</html>

data.php file

<?php
include "connection.php";

$sql = "SELECT Bookings, Destination from topflights";
$result = mysqli_query($con, $sql);

//variables
$dataX = array();
$dataY = array();

//Loop to get the data
while($row = mysqli_fetch_assoc($result)){
    array_push($dataX, $row['Destination']);
    array_push($dataY, $row['Bookings']);
}

header('Content-Type: application/json');
echo json_encode(array(
    "dataX" => $dataX,
    "dataY" => $dataY));
?>

chart.js file

function renderHtmlChart() {

    var universalOptions = {
        responsive: true,
        title: {
            display: true,
            text: "Top 5 Flights Booked in the Year"
        },
        legend: {
            display: false,
        },
        scales: {
            xAxes: [{
                display: true,
            }],
            yAxes: [{
                display: true,
                ticks: {
                    beginAtZero: true,
                }
            }],

        }
    }

    $.ajax({
        url: 'data.php',
        method: 'GET',
        success: function(response) {
            var dataX = response.dataX;
            var dataY = response.dataY;

            var ctx = document.getElementById('myChart');

            var myChart = new Chart(ctx, {
                type: 'bar',
                data: {
                    labels: dataX,
                    datasets: [{
                        label: 'top flights',
                        data: dataY,
                        backgroundColor: ['tomato', 'green', 'blue', 'cyan', 'orange'],
                        borderWidth: 1,
                        borderColour: 'grey',
                        hoverBorderColor: 'black'
                    }],
                },
                options: universalOptions
            }
            )
        },
        error: function(response) {
            alert('ajax failed');
            console.log(response);
        }
    });
}
$(document).ready(function() {
    renderHtmlChart();
});

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.