Google pie chart with ajax request example in PHP

Hello Guys,

In the last tutorial, we have discussed how to implement Google chart in Laravel application. We have implemented Line chart.

In this tutorial, we will go through implementing Google pie chart in core PHP. We will use ajax request to get data from PHP server and render it to the chart. This will also help all frontend developers who are using Ajax request to render pie chart.

Instead of implement all code in one file, we will divide them in multiple files. This will also help to reuse code. In the first file config.php, we will connect PHP with MySQL database.

config.php

<?php

$servername = "localhost";
$username = "root";
$password = "secret";
$dbname = "chart";

// create connection
$connection = new mysqli($servername, $username, $password, $dbname);

// check connection
if ($connection->connect_error) {
    die($connection->connect_error);
}

Now in the second step, we will create a file which will fetch data from database. The request will send to this file.

chart.php

<?php

include 'config.php';

$sql = "SELECT browser, percentage FROM visitors";

$result = $connection->query($sql);

if ($result->num_rows > 0) {

    $data[0][0] = 'Browser';
    $data[0][1] = 'Percentage';
    $x = 1;
    // output data of each row
    while($row = $result->fetch_assoc()) {
        $data[$x][0] = $row["browser"];
        $data[$x][1] = (float)$row["percentage"];
        $x++;
    }
} else {
    die("No records");
}

echo(json_encode($data));

All the response from PHP server to frontend should response to Json data format because Javascipt doesn't know PHP array or object. Instead of return statement, we have placed echo statement. This way, you get data from server side to front end side.

Now in the third and last step, we will add a HTML view which will create Ajax request to server and render data to view. We will use Google CDN to implement Google chart. This way, you don't need to download library into your local project.

index.php

<!DOCTYPE html>
<html>
    <head>
        <script type="text/javascript" src="https://www.gstatic.com/charts/loader.js"></script>
        <script type="text/javascript" src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
        <script type="text/javascript">
            google.charts.load('current', {'packages':['corechart']});

            google.charts.setOnLoadCallback(drawChart);
            
            function drawChart() {

                var chartData = $.ajax({
                        url: "chart.php",
                        dataType: "json",
                        async: false
                    }).responseText;
                
                var data = google.visualization.arrayToDataTable(JSON.parse(chartData));
                
                var options = {
                    title: 'Browser percentage'
                };

                var chart = new google.visualization.PieChart(document.getElementById('piechart'));

                chart.draw(data, options);
            }
        </script>
    </head>
    <body>
        <div id="piechart" style="width: 900px; height: 500px;"></div>
    </body>
</html>

In the view, we have created the Ajax request using jQuery Ajax. Also note that we receive Json string from server response, so we have to convert it to Javascript object using JSON.parse() function.

If you want the data that we have used in example, you can always run the following query in your MySQL command.

--
-- Table structure for table `visitors`
--

CREATE TABLE `visitors` (
  `id` int NOT NULL,
  `browser` varchar(255) NOT NULL,
  `percentage` decimal(10,2) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci;

--
-- Dumping data for table `visitors`
--

INSERT INTO `visitors` (`id`, `browser`, `percentage`) VALUES
(1, 'Chrome', '69.28'),
(2, 'Edge', '7.75'),
(3, 'Firefox', '7.48'),
(4, 'Internet Explorer', '5.21'),
(5, 'Safari', '3.73'),
(6, 'Opera', '1.12'),
(7, 'Others', '5.43');

--
-- Indexes for table `visitors`
--
ALTER TABLE `visitors`
  ADD PRIMARY KEY (`id`);

--
-- AUTO_INCREMENT for table `visitors`
--
ALTER TABLE `visitors`
  MODIFY `id` int NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=8;
COMMIT;

Now run the PHP server using php -S 0.0.0.0:8000 command in Terminal and open http://localhost:8000 in the browser.

I hope you liked the article, Please feel free to send suggestion or help our mail address [email protected] or our contact us page.