STATISTICS

bar chart


In the previous article, i've constructed a pie chart. While, playing with that code for sometime i was able to draw bar chart too.

INDEX.PHP
bar chart screenshot
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" href=" style.css" type="text/css" />
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<script> 
$(document).ready(function(){

$(document).on("click", "button", function(){
 
 $.ajax({

 type: "POST",

 url: "vote.php",

 data:$("form").serialize(), 

 cache: false, 

 success: function(data){
 $("#poll").load("result.php");
 } });

return false;});
});
</script>
</head>
<body>
<div id="poll">
<h2>Which is your favourite animal?</h2>
<form>
<table>
<tr>
 <td>Elephant : </td>
 <td><input type="radio" name="v" value="1"></td>
</tr>
<tr>
 <td>Lion : </td>
 <td><input type="radio" name="v" value="2"></td> 
</tr>
 <tr>
 <td>Zebra : </td>
 <td><input type="radio" name="v" value="3"></td> 
</tr>
</table><br>
<button>Cast Vote</button>
</form>
</div>
</body> 
</html>
    

RECORD.TXT

It stores the total votes of each options in new lines.

bar chart notepad


VOTE.PHP
<?php
$vote = $_POST['v'];
$flin = file("count_vote.txt");
$i=0;
foreach($flin as $line)
{
$o[$i]=trim($line);
echo $o[$i]."end";
$i++;
}

switch($vote)
{
 case "1" : $o[0] = $o[0] + 1;
 break;
 
 case "2" : $o[1] = $o[1] + 1;
 break;
 
 case "3" : $o[2] = $o[2] + 1;
 break;
 
 default : break;
 
}
 
$text = "$o[0]\n$o[1]\n$o[2]";
echo $text;
$handle = fopen("count_vote.txt","w");
fwrite($handle,$text);
fclose($handle);
?> 

RESULT.PHP
<?php

$flin = file("count_vote.txt");

$o1 = $flin[0];
$o2 = $flin[1];
$o3 = $flin[2];
 
$tot=$o1+$o2+$o3;
 
$js_arr = json_encode($flin);
?>
<!DOCTYPE html>
<html>
<head>
<script>
 
var canvas = document.getElementById("can");
var context = canvas.getContext("2d");

var stat = php
echo $js_arr;
 ;
var tot = php echo $tot; 
var col = ["#F9E559","#6CCECB","#8EDC9D"]; 
var op=["Elephant", "Lion", "Zebra"];
var offt=0;var of=0;
context.lineWidth =4;
context.moveTo(5,10); 
context.lineTo(5, 510);
context.strokeStyle = "gray";
context.stroke(); 
context.translate(0,10); 

for(var j=500;j>=0;j=j-100)
{ 
context.fillStyle ="gray";
context.fillText(j,10, of);
of=of+100; 
}
context.translate(0,-10);
 
var x=70; 
for (var i = 0; i < stat.length; i++) {
context.fillStyle = col[i];
context.beginPath();
context.rect(x, 510-stat[i], 30, stat[i]);
context.fill();
context.fillStyle ="gray";
context.fillText(op[i],x,525); 
offt=offt+30; 
x=x+70;
}
</script>
</head>
<body>
<canvas id="can" width="300px" height="540px" style="border:1px solid #d3d3d3;">
</canvas>
</body>
</html>
    
STYLE.CSS
body
{
font-family: Arial;
font-size: 14px;  
}
#poll
{ 
width: 100%;
height: auto; 
text-align: center;
color:#333;  
}
table
{
margin:0 auto;  
color:#333;
}       


Leave a Comment  
Download Code(38)





All rights reserved, the content is copyrighted to the author.

RELATED POST