0

I'm trying to fetch data from a database, to be displayed in a graph.js graph. I understand that the callback from ajax is async and I've tried to set a timeout, awaiting the response and setting the returned values to a global variable but nothing works. Would appreciate if someone could tell me how this would work! Thanks

<body>

<canvas id="myChart"></canvas>
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.6.0/Chart.min.js"></script>
<script>
    var ctx = document.getElementById('myChart').getContext('2d');
    var response = null;

   var xhr;
   if (window.XMLHttpRequest) { // Mozilla, Safari, ...
       xhr = new XMLHttpRequest();
   } else if (window.ActiveXObject) { // IE 8 and older
       xhr = new ActiveXObject("Microsoft.XMLHTTP");
   }
   xhr.open("POST", "fetch-graph.php", true);
   xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
   xhr.send("fetch");
   xhr.onreadystatechange = display_data;
   function display_data() {
       if (xhr.readyState == 4) {
           if (xhr.status == 200) {
               console.log(xhr.responseText);
               response = xhr.responseText;
           } else {
               alert("something went wrong");
           }
       }
   }

    var timerId = setInterval(function() {
        if(response !== null) {
            var chart = new Chart(ctx, {
                // The type of chart we want to create
                type: 'line',

                // The data for our dataset
                data: {
                    labels: ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"],
                    datasets: [{
                        label: "Example Graph 1",
                        borderColor: 'rgb(255, 0, 100)',
                        //data: [45,23,39,12,34,56,67,78,90,78,73,74]
                        data: response
                    }]
                }
            });
            clearInterval(timerId);
        }
    }, 1000);

</script>
</body>

This is the php file, getting values from a db:

<?php

$connect = mysqli_connect("localhost", "max", "password", "graph");

if(isset($_POST['fetch'])){

    $sql = "SELECT * FROM graph_data";
    $query = mysqli_query($connect, $sql);

    $row = mysqli_fetch_assoc($query);

    $months = ['jan', 'feb', 'mar', 'apr', 'may', 'jun', 'jul', 'aug', 'sep', 'oct', 'nov', 'deb'];

    for ($i = 0; $i<12; $i++){
        echo $row[$months[$i]];
    }
}
2
  • Instead of echoing plain text, perhaps you should echo an encoded JSON? Commented Aug 3, 2017 at 8:30
  • tried that with json_encode in php and JSON.parse in JS but didnt work either Commented Aug 3, 2017 at 8:33

2 Answers 2

2

You can add inside the ajax response also. in js page

<script     src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.3.0/Chart.bundle.js">    </script>

$.ajax({
            url: "/your URL",
            type: "post",
            dataType: "json",
            data: send your data what you want to send ,
            success: function (response) {
                if (response) {
                    let data = response;
                    var ctx = document.getElementById("doughutChart");
                    ctx.height = 150;

                    var myChart = new Chart(ctx, {
                        type: 'doughnut',
                        data: {
                            datasets: [{
                                data: data,
                                backgroundColor: [
                                    "rgba(253, 11, 21, 0.9)",
                                    "rgba(0, 123, 255,0.7)"
                                ],
                                hoverBackgroundColor: [
                                    "rgba(253, 11, 21, 0.9)",
                                    "rgba(0, 123, 255,0.7)"
                                ]
                            }],
                            labels: [
                                "Pending",
                                "Completed"

                            ]
                        },
                        options: {
                            responsive: true
                        }
                    });
                }
            }
        });

In dynamic graph you have to send the valus in array. so in ajax response i got the value in array and pass that data inside chart.

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

Comments

1

First of all, it's better to create the graph as soon as the response is there. Also the chart expects an array, so you'd have to encode your response from the php as JSON.

<body>

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

<script>
    var ctx = document.getElementById('myChart').getContext('2d');
    var response = null;

   var xhr;
   if (window.XMLHttpRequest) { // Mozilla, Safari, ...
       xhr = new XMLHttpRequest();
   } else if (window.ActiveXObject) { // IE 8 and older
       xhr = new ActiveXObject("Microsoft.XMLHTTP");
   }
   xhr.open("POST", "fetch-graph.php", true);
   xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
   xhr.send("fetch");
   xhr.onreadystatechange = display_data;
   function display_data() {
       if (xhr.readyState == 4) {
           if (xhr.status == 200) {
               console.log(xhr.responseText);
               response = xhr.responseText;
               try{
                    var data = JSON.parse(response)
               }catch(e){
                    alert('Could not parse response from server')
                    return
               }
               createChart(data)
           } else {
               alert("something went wrong");
           }
       }
   }

    function createChart(chart_data){
        var chart = new Chart(ctx, {
        type: 'line',
        data: {
            labels: ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"],
                datasets: [{
                    label: "Example Graph 1",
                    borderColor: 'rgb(255, 0, 100)',
                    data: chart_data
                }]
            }
        });
    }

</script>
</body>

And on the serverside:

$connect = mysqli_connect("localhost", "max", "password", "graph");

$response = array();

if(isset($_POST['fetch'])){

    $sql = "SELECT * FROM graph_data";
    $query = mysqli_query($connect, $sql);

    $row = mysqli_fetch_assoc($query);

    $months = ['jan', 'feb', 'mar', 'apr', 'may', 'jun', 'jul', 'aug', 'sep', 'oct', 'nov', 'deb'];

    for ($i = 0; $i<12; $i++){
        $response[] = $row[$months[$i]];
    }
}

echo json_encode($response);

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.