Mefth Loader Gif

How to implement bar and pie charts using Chart.js with AJAX & PHP?


Last Updated: 5 months ago
Implement Chart.js with AJAX & PHP

Step-By-Step guide to creating bar & pie charts In Chart.js with AJAX & PHP

Visualizing data is a great way to make sense of it quickly and easily. This can also be incredibly helpful in presenting this data effectively to your audience, which is why bar and pie charts are so popular among developers. In this post, we'll provide you with a step-by-step guide on how to create bar and pie charts using Chart.js! With the help of code snippets, you’ll understand the basics in no time!

Overview of Bar Charts

A bar chart is a type of graph that is used to compare data sets. Bar charts are popular because they are easy to interpret and can be used to compare data sets of different sizes. Bar charts are also versatile, and can be used to compare data over time or across different categories.

To create a bar chart in Chart.js, you will need to use the barChart() method. This method takes two arguments: the data set that you want to represent as a bar chart, and an options object. The options object allows you to specify the width, height, and other settings for your chart.

Once you have created your chart, you can add it to your web page by calling the render() method. This method will take care of drawing your chart on the page.

Step-by-step guide:

  • 1) Choose the data set that you want to represent as a bar chart. This data set should be numerical, and should be organized into categories (x-axis) and values (y-axis).
  • 2) Create an options object for your chart. In this object, you can specify the width, height, and other settings for your chart.
  • 3) Call the barChart() method, passing in your data set and options object as arguments. This method will return a new Chart instance that represents your bar chart.
  • 4) Call the render() method on your Chart instance.

Setting Up Bar Charts in Chart.js

Chart.js is an open-source JavaScript library that allows you to create bar and pie charts in your web site or application. This Step-By-Step Guide will show you how to set up Chart.js and create your first bar chart theoretically.

  • 1) Include the Chart.js library in your web page. You can either download the library from the Chart.js website, or include it from a CDN (Content Delivery Network).
  • 2) Create a <canvas> element in your web page where the chart will be rendered. The <canvas> element needs to have an id attribute so that it can be referenced by Chart.js:
  • 3) Create a time drop down menu that allows the user to select between months and years.
  • 4) Create a JavaScript function that will initialize the chart.
  • 5) Define the data that will be used to create the chart. This data can be hard-coded into the JavaScript, or retrieved dynamically from an external source such as a database:
  • 6) Lets fetch data from Database.

Now Lets see the coding part of it

1) Add Chart.js and jQuery CDNs or download and hosted them on your own project.

 
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.3/jquery.min.js"></script>       
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/4.2.0/chart.min.js"></script>       

2) Now, let's create the div id where the chart will be rendered.

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

3) Lets create the months and years dropdown.

Monthly Analytics

<select id="month" class="barGraphStyler">         
        <option value="1" selected>January</option>         
        <option value="2">February</optio>         
        <option value="3">March</option>         
        <option value="4">April</option>         
        <option value="5">May</option>         
        <option value="6">June</option>         
        <option value="7">July</option>         
        <option value="8">August</option>         
        <option value="9">September</option>         
        <option value="10">October</option>         
        <option value="11">November</option>         
        <option value="12">December</option>         
</select>         
<select id="year"  class="barGraphStyler">         
<option value="2021">2021</option>          
<option value="202">2022</option>          
<option value="2023" selected>2023</option>          
</select>       

Lets decorate the drop down using CSS

.barGraphStyler{       
   padding: 10px;       
    margin: 10px auto;       
    display: inline-block;       
    font-family: inherit;       
    border-radius: 25px;       
    width: 130px;       
    cursor: pointer;       
    border: 0.3px solid #ddd;       
}       

See the result

HTML drop down

4) Now, let's create the JavaScript function that will draw the chart.

$(document).ready(function(){ // WHEN THE SCRIPT IS READY THEN MAKE A RQUEST       
  continents(); // RUN THE QUERY       
});       
$('#month, #year').change(function() { // WHEN THE MONTH OR YEAR CHANGED       
  continents(); // RUN THE QUERY       
});       
function continents() {       
  $.ajax({       
    url: "https://www.example.com/data/graph.php",       
    type: "POST",       
    dataType: 'json',  // SHOULD BE JSON       
    data:{       
        month:$("#month").val(), // GET THE MONTH FROM DROPDOWN       
        year:$("#year").val()  // GET THE YEAR FROM DROP DOWN       
    },       
    success: function(data) { // THE RESPONSE  IS IN DATA       
      var x = [];       
      var y = [];       
      for(var i in data) {       
        x.push(data[i].x);       
        y.push(data[i].y);       
      }       
      var chartdata = {       
        labels: x,       
        datasets : [       
          {       
                label: 'Views',       
                backgroundColor: '#2c95fd',       
                borderColor: '#2c95fd',       
                hoverBackgroundColor: '#2760e6',       
                hoverBorderColor: '#2760e6',       
            data: y       
          }       
        ]       
      };       
      var ctx = $("#graphCanvas");   // THIS IS TO UPEND THE RESULT IN THE DIV       
      var barGraph = new Chart(ctx, {       
        type: 'bar', // THIS IS THE STRUCTURE OF THE CHART, WITHER IT IS line, bar OR horizontalBar      
        data: chartdata       
      });       
    },       
    error: function(data) {       
        // ERROR MSG       
    }       
  });       
}         
 

5) Now, let's get data from this graph.php page.

$data = array(); // JUST CREATE ARRAY  TO UPEND LATER ON            
//===================== CREATE A DB CONNECTION SO YOU CAN HAVE ACCESS TO DB TO MINIPLATE DATA ==========       
$database_host = "localhost";                                   
$database_user = "YOUR_DATABASE_USER";                                        
$database_password = "YOUR_DATABASE_PASSWORD";                                             
$database_name = "YOUR_DATABASE_NAME";                     
$db_conn = mysqli_connect($database_host, $database_user, $database_password, $database_name);                      
if($db_conn !== TRUE){     // IF THE CONNECTION IS NOT TRUE       
	$data[] =  [       
        'x' => "Error",       
        'y' => "Sorry there is something wrong with our System, Please try again later!"       
    ];                            
}else{           
if($_SERVER['REQUEST_METHOD'] === 'POST'){ // MUST BE POST REQUEST TO PREVENT DIRECT ENTERANCE TO THE PAGE BY WRITING OUR PHP FILE URL                            
$year = (int)mysqli_real_escape_string($db_conn , $_POST['year']); // THE YEAR VALUE       
$month = (int)mysqli_real_escape_string($db_conn , $_POST['month']); // TH MONTH VALUE       
if(!in_array($month, array("1", "2", "3", "4", "5", "6", "7", "8", "9", "10", "11", "12"), TRUE) || !in_array($year, array("2022", "2023"), TRUE)){  //JUST TO MAKE SURE THAT THE MONTH & YEAR ARE WITHIN THE ARRAY OF THE GIVEN DATA       
$chart_data_count = $db_conn ->query("SELECT COUNT(id), continents FROM main_db WHERE email = '$email' AND MONTH(time) = '$month' AND YEAR(time) = '$year' AND  GROUP BY continents "); // LETS GET DATA       
foreach ($chart_data_count as $chart_data) {       
	$data[] =  [       
        'x' => mb_substr($chart_data["continents"], -2),       
        'y' => $chart_data["COUNT(id)"]       
    ];       
  }else{       
	$data[] =  [       
        'x' => "Error",       
        'y' => "Sorry there is something wrong with our System, Please try again later!"       
    ];        
  }       
}       
}else{       
	$data[] =  [       
        'x' => "Error",       
        'y' => "Sorry there is something wrong with our System, Please try again later!"       
    ];        
}       
// GET ALL THE RESPECTIVE RESPONSE AND REPLY TO THE CLIENT       
echo json_encode($data); // json_encode // TO OUTPUT JSON STRUCTURED DATA       
$db_conn->close();     
 

Now, Lets see the above code JSON response

[       
    {       
        "x": "Oceania",       
        "y": "8"       
    },       
    {       
        "x": "South America",       
        "y": "11"       
    },       
    {       
        "x": "Asia",       
        "y": "315"       
    },       
    {       
        "x": "Europe",       
        "y": "588"       
    },       
    {       
        "x": "North America",       
        "y": "705"       
    },       
    {       
        "x": "Africa",       
        "y": "2582"       
    }       
]       
 

See this in the browser developer tool of the AJAX response

AJAX response

Now see the result in bar shaped

Bar Graph using Chart.js

Now You may want the bar graph in horizontal shaped. So you have to change type: 'bar', to type: 'horizontalBar',

Horizontal Bar graph using Chart.js

Now You may want the bar graph in line shaped. So you have to change type: 'bar', to type: 'line',

Line Bar graph using Chart.js

When it comes to data visualization, there are many different types of charts that can be used to represent data. Pie charts are one such type of chart that can be used to show the relative sizes of different data points. To see the data in a pie shaped, change this type: 'bar', to type: 'pie',

pie graph using Chart.js
Keep in mind that you have to have different colors for this pie chart to be attractive, So you have to replace the current background color with backgroundColor: ["#FAC0CB", "#0000FF", "#00AFFF", "#FFC500", "#FFFF50","#FFA000"],
Keep in mind if you want to change the order of the data either ASC or DESC order just add ORDER BY COUNT(id) DESC at the end of you SQL query

Options for Customizing Your Bar Charts

Bar charts are one of the most common ways to visualize data. But there's no need to stick to the default settings. With Chart.js, it's easy to create responsive, stylish, and customizable bar charts.

Here are some options for customizing your bar charts:

  • Change the color of your bars
  • Add or remove labels
  • Change the width of your bars
  • Add a title or legend
  • Stack your bars

The advantages of adding this Chart.js Library to your project along with AJAX & and PHP implementation is that your users can select and view data from different months and/or years.

Conclusion

Chart.js is an incredibly useful library for creating bar and pie charts quickly and easily. With the right data, it can be a great tool for visualizing data in your website or application. By following our simple step-by-step guide here, you should have no trouble getting started with charting in Chart.js! Now that you know how to use it to create beautiful charts, why not go ahead and start experimenting?

Writer Image Kifle Tesfay

Full stack Web developer, Founder of Mefth and Userparser.

Report for Comment or Reply




Mefth Loader gif

Login to Write... comment.

You must Login to write Comment.

Subscribe

Get Notified through your email for new Blogs.

You may like these posts