0

Good day! I have a Morris Chart that I want to supply a value from PHP to jQuery. I've done searching here in stackoverflow.com but I can't find a suitable solution based on my problem. Can anyone provide an answer plus explanation on how that code works?

I notice on the jQuery code it's already inside a function. My problem is how can I call a function using events in JavaScript? I don't know how to create a jQuery function.

Here are code:

(function ($) {
            "use strict";
            var mainApp = {

                main_fun: function () {
                    /*====================================
                    METIS MENU 
                    ======================================*/
                    $('#main-menu').metisMenu();

                    /*====================================
                      LOAD APPROPRIATE MENU BAR
                   ======================================*/
                    $(window).bind("load resize", function () {
                        if ($(this).width() < 768) {
                            $('div.sidebar-collapse').addClass('collapse')
                        } else {
                            $('div.sidebar-collapse').removeClass('collapse')
                        }
                    });

                    /*====================================
                  MORRIS DONUT CHART
               ======================================*/
                    Morris.Donut({
                        element: 'morris-donut-chart',
                        data: [{
                            label: "2017-2018-1",
                            value: 3000
                        }, {
                            label: "2017-2018-2",
                            value: 4000
                        }],
                        resize: true
                    });           
             
                },

                initialization: function () {
                    mainApp.main_fun();

                }

            }
            // Initializing ///

            $(document).ready(function () {
                mainApp.main_fun();
            });

        }(jQuery));
<div id="page-inner">
  <div class="row">
      <div class="col-md-12">
       <h2>Total Enrolled Students</h2>   
          <h5>Welcome Jhon Deo , Love to see you back. </h5>

      </div>
  </div>
   <!-- /. ROW  -->
   <hr />
  <div class="row">
      <div class="col-md-6 col-sm-12 col-xs-12">                     
          <div class="panel panel-default">
              <div class="panel-heading">
                  Donut Chart Example
              </div>
              <div class="panel-body">
                  <div id="morris-donut-chart"></div>
              </div>
          </div>            
      </div>                           
  </div>
<!-- /. ROW  -->
</div>

Here's the Screenshot enter image description here

UPDATE #1

HTML

$getSYList = loadSchoolYearList();
$loadSemCount = getTotalStudListEverySem();

FUNCTION

function loadSchoolYearList(){
    include '..\assets\database\connect.php';
    $list = array();
    $i = 0;
    $query = "SELECT DISTINCT schoolYear FROM tblschoolyear";
    $result = $conn->query($query);
    if ($result->num_rows > 0) {
        while($row = $result->fetch_assoc()) {  
            $list[$i][] = $row['schoolYear'];   
            $i++;
        }
    }
    return $list;
}

function getTotalStudListEverySem(){
    include '..\assets\database\connect.php';
    $i = 0;
    $count = 1;
    $sem = 1;
    $semList = array();
    $schoolYearCount = 0;

    // Count tblschoolyear record
    $query = "SELECT COUNT(syId) as totalSY FROM tblschoolyear";
    $stmt = $conn->prepare($query);
    $stmt->execute();
    $stmt->store_result();

    if($stmt->num_rows > 0){
        $stmt->bind_result($schoolYearCount);
        while($stmt->fetch()) {
            $schoolYearCount=$schoolYearCount;
        }
    }

    for($count;$count<=$schoolYearCount;$count++){
        $query = "SELECT COUNT(r.infoId) as totalSemCount FROM tblreg as r ";
        $query .= "INNER JOIN tblschoolyear as sy ON sy.syId=r.syId ";
        $query .= "INNER JOIN tblstudinfo as i ON r.infoID=i.infoID WHERE sy.syID=". $count ." AND sy.SchoolSem=". $sem ."";
        $result = $conn->query($query);
        if ($result->num_rows > 0) {
            while($row = $result->fetch_assoc()) {  
                $semList[$i][] = $row['totalSemCount']; 
                $i++;
            }
        }
        if ($sem==2){
            $sem = 1;
        }else{
            $sem++;             
        }
    }       
    $conn->close();
    return $semList;            
}

the result will be these:

$getSYList[0][0] = 2016-2017
$getSYList[1][0] = 2017-2018

why? because as you notice on the code there is DISTINCT on the query for loadSchoolYearList()

these are the original value:

syID
1
schoolYear
2016-2017
Sem
1

syID
2
schoolYear
2016-2017
Sem
2

syID
3
schoolYear
2017-2018
Sem
1

syID
4
schoolYear
2017-2018
Sem
2

So I have already for the title on the graph

Next are the values:

$loadSemCount value will be

2016-2017
1st Sem
$loadSemCount(0)(0) = 381 students
2nd Sem
$loadSemCount(1)(0) = 2533 students

2017-2018
1st Sem
$loadSemCount(0)(0) = 2931 students
2nd Sem
$loadSemCount(1)(0) = 2273 students

After I retrieve all that data my problem is how will I convert your static code to dynamic code... when the page load that data will pass on the "data=[]" and will load on the chart.

and this will be the final result when in dynamic enter image description here but for this screeen shot it's only a static code provided by rinu

Hope my long explanation will enlighten my problem... sorry for my english

UPDATE # 2

First I will change the Morris Donut to Bar Graph

this is the static code for the Bar Graph

$data = [
            [
                'y' => $loadSemCount[0][0],
                'a' => $loadSemCount[0][1],
                'b' => $loadSemCount[1][1]
            ],
            [
                'y' => $loadSemCount[2][0],
                'a' => $loadSemCount[2][1],
                'b' => $loadSemCount[3][1]
            ]
        ];

Morris Script

Morris.Bar({
            element: 'morris-bar-chart',
            data: chartData,
            xkey: 'y',
            ykeys: ['a', 'b'],
            labels: ['1st Sem', '2nd Sem'],
            hideHover: 'auto',
            resize: true
        });       

I re-code my SQL as @rinu said:

SELECT sy.schoolYear, COUNT(sy.syID) as totalRegStud FROM tblreg as r 
INNER JOIN tblschoolyear as sy ON sy.syId=r.syID GROUP BY sy.schoolYear, sy.schoolSem

and this is the result:

2016-2017   381
2016-2017   2533
2017-2018   2932
2017-2018   2273

and this is the code where I will put the code to $data array:

for($i;$i<count($loadSemCount);$i++){

    if($carry!=$loadSemCount[$i][0]){
        echo $loadSemCount[$i][0] . '<br>';
        echo $loadSemCount[$i][1] . '<br>';
        $data[$i][] = $loadSemCount[$i][0];
        $data[$i][] = $loadSemCount[$i][1];
    }else{
        $data[$i][] = $loadSemCount[$i][1];
        echo $loadSemCount[$i][1] . '<br>';            
    }
    $carry=$loadSemCount[$i][0];
}

and this is the Morris Bar Graph result... enter image description here

one of my problem solve, I have the 'y' which is '2016-2017' and the value which are 'a' as '381' & 'b' as '253' on the first loop and so on

the second problem is HOW can I insert that data into the morris chart using loop? based on the screenshot it says undefined?

UPDATE # 3

as I use var_dump on the dynamic code and static code there are difference..

dynamic code var_dump:

array(4) { [0]=> array(2) { [0]=> string(9) "2016-2017" [1]=> string(3) "381" } [1]=> array(1) { [0]=> string(4) "2533" } [2]=> array(2) { [0]=> string(9) "2017-2018" [1]=> string(4) "2932" } [3]=> array(1) { [0]=> string(4) "2273" } } 

static code var_dump:

array(2) { [0]=> array(3) { ["y"]=> string(9) "2016-2017" ["a"]=> string(3) "381" ["b"]=> string(4) "2533" } [1]=> array(3) { ["y"]=> string(9) "2017-2018" ["a"]=> string(4) "2932" ["b"]=> string(4) "2273" } }

can anyone share his/her code to insert the y value as 2016-2017 and a & b value as 381 & 2533?

UPDATE #4

I manage to put my data in the array with the key value of y,a & b but still it won't appear on my chart.

my code:

for($i;$i<count($loadSemCount);$i++){

    if($carry!=$loadSemCount[$i][0]){
        $data[$i]['y'] = $loadSemCount[$i][0];    // 2016-2017 / 2017-2018
        $data[$i]['a'] = $loadSemCount[$i][1];    // 381       / 2533
    }else{
        $data[$i-1]['b'] = $loadSemCount[$i][1];  // 2932      / 2273           
    }
    $carry=$loadSemCount[$i][0];
}

Note:

This is the var_dump for my Dynamic Value:

array(2) { [0]=> array(3) { ["y"]=> string(9) "2016-2017" ["a"]=> string(3) "381" ["b"]=> string(4) "2533" } [2]=> array(3) { ["y"]=> string(9) "2017-2018" ["a"]=> string(4) "2932" ["b"]=> string(4) "2273" } } 

And var_dump for Static Value:

array(2) { [0]=> array(3) { ["y"]=> string(9) "2016-2017" ["a"]=> string(3) "381" ["b"]=> string(4) "2533" } [1]=> array(3) { ["y"]=> string(9) "2017-2018" ["a"]=> string(4) "2932" ["b"]=> string(4) "2273" } }

and this is the code of Static Value

$data = [
            [
                'y' => '2016-2017',
                'a' => '381',
                'b' => '2533'
            ],
            [
                'y' => '2017-2018',
                'a' => '2932',
                'b' => '2273'
            ]
        ];

as you notice It's the same but still no Bar Chart.

Source: https://stackoverflow.com/a/30050395/7514462

UPDATE #5 - hopefully my last update

Dynamic var_dump

array(2) { [0]=> array(3) { ["y"]=> string(9) "2016-2017" ["a"]=> string(3) "381" ["b"]=> string(4) "2533" } **[2]**=> array(3) { ["y"]=> string(9) "2017-2018" ["a"]=> string(4) "2932" ["b"]=> string(4) "2273" } }

Static var_dump

array(2) { [0]=> array(3) { ["y"]=> string(9) "2016-2017" ["a"]=> string(3) "381" ["b"]=> string(4) "2533" } **[1]**=> array(3) { ["y"]=> string(9) "2017-2018" ["a"]=> string(4) "2932" ["b"]=> string(4) "2273" } }

as you notice on the in both Dynamic and Static has value of

**[n]**

because of this code

for($i;$i<count($loadSemCount);$i++){

    if($carry!=$loadSemCount[$i][0]){
        // echo $loadSemCount[$i][0] . '<br>';
        // echo $loadSemCount[$i][1] . '<br>';
        $data[$i]['y'] = $loadSemCount[$i][0];
        $data[$i]['a'] = $loadSemCount[$i][1];
    }else{
        $data[$i-1]['b'] = $loadSemCount[$i][1];
        // echo $loadSemCount[$i][1] . '<br>';            
    }
    $carry=$loadSemCount[$i][0];
}

can anyone here re-code my SQL?

From this:

Column 1    Column 2
2016-2017   381
2016-2017   2533
2017-2018   2932
2017-2018   2273

To this:

Column 1    Column 2  Column 3
2016-2017   381       2533
2017-2018   2932      2273

this is my current SQL code:

SELECT sy.schoolYear, COUNT(sy.syID) as totalRegStud FROM tblreg as r
INNER JOIN tblschoolyear as sy ON sy.syId=r.syID GROUP BY sy.schoolYear, sy.schoolSem
sg7
  • 6,108
  • 2
  • 32
  • 40
Mark
  • 73
  • 2
  • 12
  • 1
    Is your problem passing dynamic data from PHP to your javascript chart function? You don't need a "jquery function" for that. – Heinrich Lee Yu Jan 17 '18 at 09:38
  • thanks for the info... If you have an answer please post it I will try also @rinu's answer. :-) – Mark Jan 18 '18 at 00:37

1 Answers1

1

If the data is static, meaning you have to reload the entire page to update the chart, then the easiest solution is a global JavaScript variable.

In the HTML

<?php

$data = [];

$res = $conn->query('SELECT sy.schoolYear, sy.schoolSem, COUNT(*) AS totalRegStud FROM tblreg as r 
INNER JOIN tblschoolyear AS sy ON sy.syId = r.syID GROUP BY sy.syId');
while ($res && $row = $res->fetch_assoc()) {
    $data[] = [
        'label' => $row['schoolYear'] . '-' . $row['schoolSem'],
        'value' => (int)$row['totalRegStud']
    ];
}
?>
<script>var chartData = <?=json_encode($data)?>;</script>

In your script

Morris.Donut({
    element: 'morris-donut-chart',
    data: chartData,
    resize: true
});
rinu
  • 989
  • 1
  • 7
  • 14
  • thanks @rinu for your answer... nope... it's not static... I just put a static value as a sample where the data must fill-in.... I'll try to convert your solution to dynamic and I will comment or edit my post if it will work... :-) – Mark Jan 18 '18 at 00:36
  • I tried to convert it to dynamic but I can't figure it out... can you edit your answer to make it dynamic? thanks in advance – Mark Jan 18 '18 at 08:21
  • Where does your data come from? Is there a refresh timer or button on the page? Do you reload the page to update? In any case I would need to see the full code you're working with to make that happen. – rinu Jan 18 '18 at 08:24
  • You need to loop both `$getSYList` and `$loadSemCount` and combine the data into a new array. This new array should have the `label` and `value` keys format. `label` comes from `$getSYList` and `value` comes from `$loadSemCount`. Can you manage that? – rinu Jan 18 '18 at 15:49
  • Perhaps an easier solution would be to rewrite the whole PHP part and create the correct array format in the first place. You only need one function and one SQL query. The query would be `SELECT schoolYear, COUNT(syId) as totalSY FROM tblschoolyear GROUP BY schoolYear` – rinu Jan 18 '18 at 15:59
  • please review my last update #5... is there a way to merge the two similar 2016-2017 and make it 1 row? – Mark Jan 19 '18 at 11:05
  • I've updated the answer with what I think will work. I can't run the code of course to test it. – rinu Jan 20 '18 at 09:40
  • Good day @rinu sorry for late reply... Your query result are like on my post please see my update #5 at "can anyone here re-code my SQL? From this:". I solved my problem but not in professional way :-( I just create a tblstattemp and retrieve again the data from tblstattemp and put into the array. – Mark Jan 25 '18 at 09:36
  • I don't think you can count like that in SQL. If it's possible It's beyond my level of SQL skills. I would group course counts by year in PHP as shown in my code. – rinu Jan 26 '18 at 12:03
  • It's ok @rinu... I'm happy that you stick to my problem... I think the way that I create the db is wrong ... thanks by the way for helping me you gave me hint/tip on the array side :-) – Mark Jan 26 '18 at 23:53