Integrating dynamic chart from database to ionic app

Posted on Posted in Intermediate

In this tutorial, we are going to learn how to integrate dynamic chart from database to ionic application, we are going to use Chart.js library to display our database information in chart and graph format.

First, let’s list what we need to do to achieve our task of the day.

  1. Create an ionic app called chartApp
  2. Install Chart.js library
  3. Setup chart and graph template in home.html page
  4. Create chart and graph in home.ts page
  5. Test our app
  6. Create table in our database
  7. Update home.ts to fetch data from database
  8. Create a php file to fetch data from database.
  9. Test our app

Ugh!! That’s quiet some work to do, let get started.

 

Are you READY?



  1. Create an ionic app called chartApp

Open you command Line Interface(CLI) and issue the following command

ionic start chartApp blank

 

2.   Install Chart.js library

Change directory to chartApp and install Chart.js with the following command as shown below

npm install chart.js –save

chartApp chart.js installation




 

3. Setup chart and graph template in home.html page

Open home.html page and update the content between <ion-content> </ion-content> tag as shown below

<ion-content>

<ion-card>

      <ion-card-header>

        Bar Chart

      </ion-card-header>

      <ion-card-content>

        <canvas #barCanvas></canvas>

      </ion-card-content>

    </ion-card>

    <ion-card>

      <ion-card-header>

        Doughnut Chart

      </ion-card-header>

      <ion-card-content>

        <canvas #doughnutCanvas></canvas>

      </ion-card-content>

    </ion-card>

    <ion-card>

      <ion-card-header>

        Line Chart

      </ion-card-header>

      <ion-card-content>

        <canvas #lineCanvas></canvas>

      </ion-card-content>

    </ion-card>

</ion-content>




4. Create chart and graph in home.ts page

Open home.ts and update content with the code below

import { Component, ViewChild } from ‘@angular/core’;

import { NavController } from ‘ionic-angular’;

import { Chart } from ‘chart.js’;

@Component({

  selector: ‘page-home’,

  templateUrl: ‘home.html’

})

export class HomePage {

    @ViewChild(‘barCanvas’) barCanvas;

    @ViewChild(‘doughnutCanvas’) doughnutCanvas;

    @ViewChild(‘lineCanvas’) lineCanvas;

    barChart: any;

    doughnutChart: any;

    lineChart: any;

    constructor(public navCtrl: NavController) {

    }

    ionViewDidLoad() {

        this.barChart = new Chart(this.barCanvas.nativeElement, {

            type: ‘bar’,

            data: {

                labels: [“Apple”, “Mango”, “Cherries”, “Orange”],

                datasets: [{

                    label: ‘# of Votes’,

                    data: [15, 19, 5, 10],

                    backgroundColor: [

                        ‘rgba(255, 99, 132, 0.2)’,

                        ‘rgba(54, 162, 235, 0.2)’,

                        ‘rgba(255, 206, 86, 0.2)’,

                        ‘rgba(75, 192, 192, 0.2)’

                    ],

                    borderColor: [

                        ‘rgba(255,99,132,1)’,

                        ‘rgba(54, 162, 235, 1)’,

                        ‘rgba(255, 206, 86, 1)’,

                        ‘rgba(75, 192, 192, 1)’

                    ],

                    borderWidth: 1

                }]

            },

            options: {

                scales: {

                    yAxes: [{

                        ticks: {

                            beginAtZero:true

                        }

                    }]

                }

            }

        });

        this.doughnutChart = new Chart(this.doughnutCanvas.nativeElement, {

            type: ‘doughnut’,

            data: {

              labels: [“Apple”, “Mango”, “Cherries”, “Orange”],

                datasets: [{

                    label: ‘# of Votes’,

                    data: [15, 19, 5, 10],

                    backgroundColor: [

                        ‘rgba(255, 99, 132, 0.2)’,

                        ‘rgba(54, 162, 235, 0.2)’,

                        ‘rgba(255, 206, 86, 0.2)’,

                        ‘rgba(75, 192, 192, 0.2)’

                    ],

                    hoverBackgroundColor: [

                        “#FF6384”,

                        “#36A2EB”,

                        “#FFCE56”,

                        “#FF6384”

                    ]

                }]

            }

        });

        this.lineChart = new Chart(this.lineCanvas.nativeElement, {

            type: ‘line’,

            data: {

                labels: [“Apple”, “Mango”, “Cherries”, “Orange”],

                datasets: [

                    {

                        label: “My First dataset”,

                        fill: false,

                        lineTension: 0.1,

                        backgroundColor: “rgba(75,192,192,0.4)”,

                        borderColor: “rgba(75,192,192,1)”,

                        borderCapStyle: ‘butt’,

                        borderDash: [],

                        borderDashOffset: 0.0,

                        borderJoinStyle: ‘miter’,

                        pointBorderColor: “rgba(75,192,192,1)”,

                        pointBackgroundColor: “#fff”,

                        pointBorderWidth: 1,

                        pointHoverRadius: 5,

                        pointHoverBackgroundColor: “rgba(75,192,192,1)”,

                        pointHoverBorderColor: “rgba(220,220,220,1)”,

                        pointHoverBorderWidth: 2,

                        pointRadius: 1,

                        pointHitRadius: 10,

                        data: [15, 19, 5, 10],

                        spanGaps: false,

                    }

                ]

            }

        });

    }

}

 




 

5. Test your app

At this point we have hard coded the data into our codes, though that is not our mission, but it is always nice to check with hard coded data before fetching data from database, we can easily trace the problem in case something goes wrong.

Now, let’s test our app by issuing he following code

ionic serve –l

Do you have this?

chartApp first result




 

6. Create table in our database

Now that our chart is set with hard coded data, let’s us create a table in our database and seed it with our fictitious data

Now, let head to our database and create a table called fruits with the following column and data type:

  • id – int(11) –  auto-incremental
  • fruit – varchar(25)
  • quantity – int(11)

as shown below

chartapp table structure

Now, let’s seed the table with the data below

id fruit quantity
1 Apple 15
2 Mango 19
3 Cherries 5
4 Orange 10




 

7. Update home.ts to fetch data from database

Open home.ts, update the contents as shown below

import { Component, ViewChild} from ‘@angular/core’;

import {  NavController, AlertController } from ‘ionic-angular’;

import { LoadingController } from ‘ionic-angular’;

import {Http, Headers, RequestOptions}  from “@angular/http”;

import { Chart } from ‘chart.js’;

import ‘rxjs/add/operator/map’;

@Component({

  selector: ‘page-home’,

  templateUrl: ‘home.html’

})

export class HomePage {

    @ViewChild(‘barCanvas’) barCanvas;

    @ViewChild(‘doughnutCanvas’) doughnutCanvas;

    @ViewChild(‘lineCanvas’) lineCanvas;

    barChart: any;

    doughnutChart: any;

    lineChart: any;

    items:any;

    var_x:any;

    var_y:any;

    constructor(public navCtrl: NavController,   public loading: LoadingController,

      public alertCtrl: AlertController, public http: Http)  {

    }

    ionViewDidLoad() {

      var headers = new Headers();

      headers.append(“Accept”, ‘application/json’);

      headers.append(‘Content-Type’, ‘application/json’ );

      let options = new RequestOptions({ headers: headers });

     

    let loader = this.loading.create({

      content: ‘Processing please wait…’,

    });

       loader.present().then(() => {

     this.http.post(‘http://ionicdon.com/mobile/fetch_fruits_info.php’,options)

    .map(res => res.json())

    .subscribe(res => {

    loader.dismiss()

    this.items=res.server_response;

    this.var_x = this.items.map(item => item.fruit);

    this.var_y= this.items.map(item => item.quantity);

        this.barChart = new Chart(this.barCanvas.nativeElement, {

            type: ‘bar’,

            data: {

                labels: this.var_x,

                datasets: [{

                    label: ‘# of Votes’,

                    data: this.var_y,

                    backgroundColor: [

                        ‘rgba(255, 99, 132, 0.2)’,

                        ‘rgba(54, 162, 235, 0.2)’,

                        ‘rgba(255, 206, 86, 0.2)’,

                        ‘rgba(75, 192, 192, 0.2)’

                    ],

                    borderColor: [

                        ‘rgba(255,99,132,1)’,

                        ‘rgba(54, 162, 235, 1)’,

                        ‘rgba(255, 206, 86, 1)’,

                        ‘rgba(75, 192, 192, 1)’

                    ],

                    borderWidth: 1

                }]

            },

            options: {

                scales: {

                    yAxes: [{

                        ticks: {

                            beginAtZero:true

                        }

                    }]

                }

            }

        });

        this.doughnutChart = new Chart(this.doughnutCanvas.nativeElement, {

            type: ‘doughnut’,

            data: {

              labels: this.var_x,

                datasets: [{

                    label: ‘# of Votes’,

                    data: this.var_y,

                    backgroundColor: [

                        ‘rgba(255, 99, 132, 0.2)’,

                        ‘rgba(54, 162, 235, 0.2)’,

                        ‘rgba(255, 206, 86, 0.2)’,

                        ‘rgba(75, 192, 192, 0.2)’

                    ],

                    hoverBackgroundColor: [

                        “#FF6384”,

                        “#36A2EB”,

                        “#FFCE56”,

                        “#FF6384”

                    ]

                }]

            }

        });

        this.lineChart = new Chart(this.lineCanvas.nativeElement, {

            type: ‘line’,

            data: {

                labels: this.var_x,

                datasets: [

                    {

                        label: “My First dataset”,

                        fill: false,

                        lineTension: 0.1,

                        backgroundColor: “rgba(75,192,192,0.4)”,

                        borderColor: “rgba(75,192,192,1)”,

                        borderCapStyle: ‘butt’,

                        borderDash: [],

                        borderDashOffset: 0.0,

                        borderJoinStyle: ‘miter’,

                        pointBorderColor: “rgba(75,192,192,1)”,

                        pointBackgroundColor: “#fff”,

                        pointBorderWidth: 1,

                        pointHoverRadius: 5,

                        pointHoverBackgroundColor: “rgba(75,192,192,1)”,

                        pointHoverBorderColor: “rgba(220,220,220,1)”,

                        pointHoverBorderWidth: 2,

                        pointRadius: 1,

                        pointHitRadius: 10,

                        data: this.var_y,

                        spanGaps: false,

                    }

                ]

            }

        });

    });

  });

}

}




8. Create a php file to fetch data from database.

<?php

if (isset($_SERVER[‘HTTP_ORIGIN’])) {

        header(“Access-Control-Allow-Origin: {$_SERVER[‘HTTP_ORIGIN’]}”);

        header(‘Access-Control-Allow-Credentials: true’);

        header(‘Access-Control-Max-Age: 86400’);    // cache for 1 day

    }

    // Access-Control headers are received during OPTIONS requests

    if ($_SERVER[‘REQUEST_METHOD’] == ‘OPTIONS’) {

        if (isset($_SERVER[‘HTTP_ACCESS_CONTROL_REQUEST_METHOD’]))

            header(“Access-Control-Allow-Methods: GET, POST, OPTIONS”);        

        if (isset($_SERVER[‘HTTP_ACCESS_CONTROL_REQUEST_HEADERS’]))

            header(“Access-Control-Allow-Headers:        {$_SERVER[‘HTTP_ACCESS_CONTROL_REQUEST_HEADERS’]}”);

        exit(0);

    }

           

require “dbconnect.php”;

$sql =”SELECT * from fruits   ;”;

$result = mysqli_query($con, $sql);

$response = array();

while($row = mysqli_fetch_array($result))

{

            array_push($response, array(“id”=>$row[0],

                                                                                           “fruit”=>$row[1],

                                                                                           “quantity”=>$row[2] ));

           }

echo json_encode(array(“server_response”=> $response));

mysqli_close($con)

?>

Save this file as fetch_fruits_info.php



 

9. Test our app

Now that everything is set, let’s test to see our final output

chartApp first result




Leave a Reply

Your email address will not be published. Required fields are marked *