Langtrainer: Open Flash Chart-OFC

De Wikijoan
Dreceres ràpides: navegació, cerca

Totes les explicacions estan a http://teethgrinder.co.uk/open-flash-chart-2/, la pàgina web del projecte. Concretament, és bo seguir el tutorial, on de forma incremental es van mostrant diferents possiblitats d'implementar les gràfiques.

A nosaltres ens interessa dades que vinguin del MySQL.

histograma_ofc.php

Hi ha una petita diferència en com obtenim les dades en el fitxer histograma_ofc.php i histograma_ofc2.php. En la primera la select ens dóna ja les dades correctes, mitjançant un group by i utilitzant ROUND() per tal que els percentatges estiguin agrupats: 0, 10, 20,... D'aquesta manera el que obtinc de la select ho puc ficar directament en matrius i construir la gràfica.

<?php
//pintem una gràfica a partir de la informació emmagatzemada en una base de dades. Tot està contingut en un sol fitxer, i no fem servir cap tècnica d'AJAX

//accedim a la bd i recuperem la informació que ens interessa
include 'config_db.php';
include 'open_db.php';
$sql="select (round(probability/10))*10, count(*) from WORD group by round(probability/10) order by probability";
$rs = mysql_query($sql,$conn); 

$data_probability = array();
$data_count = array();
$y_max=0;

$rs = mysql_query($sql,$conn);
while( $row = mysql_fetch_array($rs) )
{
  $data_probability[] = $row[0];
  $data_count[] = floatval($row[1]);
  if ($y_max<$row[1]) $y_max=$row[1];
 }

//print_r($data_count);
print_r($data_probability);

include 'close_db.php';

//construim la gràfica
include 'php-ofc-library/open-flash-chart.php';

$title = new title( date("D M d Y") );

$bar = new bar();
//$bar->set_values( array(9,8,7,6,5,4,3,2,1) );
$bar->set_values( $data_count );

$chart = new open_flash_chart();
$chart->set_title( $title );
$chart->add_element( $bar );

$x_axis = new x_axis();
$x_labels = new x_axis_labels();
$x_labels->set_labels($data_probability);
$x_axis->set_labels( $x_labels);
$chart->set_x_axis($x_axis);
	
$y_axis = new y_axis(); 
$y_axis->set_range(0,$y_max,10);
$chart->set_y_axis( $y_axis );

//
// This is the VIEW section:
//

?>

<html>
<head>

<script type="text/javascript" src="js/json/json2.js"></script>
<script type="text/javascript" src="js/swfobject.js"></script>
<script type="text/javascript">
swfobject.embedSWF("open-flash-chart.swf", "my_chart", "350", "200", "9.0.0");
</script>

<script type="text/javascript">

function ofc_ready()
{
    //alert('ofc_ready');
}

function open_flash_chart_data()
{
    //alert( 'reading data' );
    return JSON.stringify(data);
}

function findSWF(movieName) {
  if (navigator.appName.indexOf("Microsoft")!= -1) {
    return window[movieName];
  } else {
    return document[movieName];
  }
}
    
var data = <?php echo $chart->toPrettyString(); ?>;

</script>


</head>
<body>

<p>Hisotgrama sobre probabilitats de sortir les paraules</p>


<div id="my_chart"></div>
     

</body>
</html>

histograma_ofc2.php

En aquest cas no faig un goup by, i l'agrupament de les dades es fa en el codi PHP. Per tant, és una mica diferent i com a conseqüència obtinc les barres 10, 20, 30,... (no hi ha la barra 0)

<?php
//pintem una gràfica a partir de la informació emmagatzemada en una base de dades. Tot està contingut en un sol fitxer, i no fem servir cap tècnica d'AJAX

//accedim a la bd i recuperem la informació que ens interessa
include 'config_db.php';
include 'open_db.php';
//$sql="select probability, count(*) from WORD group by probability order by probability";
$sql="select probability from WORD order by probability";
$rs = mysql_query($sql,$conn); 

$data_count = array();

$rs = mysql_query($sql,$conn);
while( $row = mysql_fetch_array($rs) )
{
  //$data_probability[] = $row[0];
  //$data_count[] = floatval($row[1]);
  switch (intval ($row[0] / 10)+1) {
    case 1:
        $data_count[0]++;
        break;  
    case 2:
        $data_count[1]++;
        break;  
    case 3:
        $data_count[2]++;
        break;  
    case 4:
        $data_count[3]++;
        break;  
    case 5:
        $data_count[4]++;
        break;  
    case 6:
        $data_count[5]++;
        break;  
    case 7:
        $data_count[6]++;
        break;  
    case 8:
        $data_count[7]++;
        break;  
    case 9:
        $data_count[8]++;
        break;  
    case 10:
        $data_count[9]++;
        break; 
}

  //if ($y_max<$row[1]) $y_max=$row[1];
 }

$y_max=0;
//for ($valorActual in $data_count) { 
foreach($data_count as $key=>$value){
  if ($value>$y_max) {$y_max=$value;}
}

//print_r($data_count);

include 'close_db.php';

//construim la gràfica
include 'php-ofc-library/open-flash-chart.php';

$title = new title( date("D M d Y") );

$bar = new bar_glass();
//$bar->set_values( array(10,9,8,7,6,5,4,3,2,1) );
$bar->set_values( $data_count );

$chart = new open_flash_chart();
$chart->set_title( $title );
$chart->add_element( $bar );

$x_axis = new x_axis();
$x_labels = new x_axis_labels();
$x_labels->set_labels(array("10","20","30","40","50","60","70","80","90","100")); //els labels han de ser char
$x_axis->set_labels( $x_labels);
$chart->set_x_axis($x_axis);
	
$y_axis = new y_axis(); 
$y_axis->set_range(0,$y_max,10);
$chart->set_y_axis( $y_axis );

//
// This is the VIEW section:
//

?>

<html>
<head>

<script type="text/javascript" src="js/json/json2.js"></script>
<script type="text/javascript" src="js/swfobject.js"></script>
<script type="text/javascript">
swfobject.embedSWF("open-flash-chart.swf", "my_chart", "350", "200", "9.0.0");
</script>

<script type="text/javascript">

function ofc_ready()
{
    //alert('ofc_ready');
}

function open_flash_chart_data()
{
    //alert( 'reading data' );
    return JSON.stringify(data);
}

function findSWF(movieName) {
  if (navigator.appName.indexOf("Microsoft")!= -1) {
    return window[movieName];
  } else {
    return document[movieName];
  }
}
    
var data = <?php echo $chart->toPrettyString(); ?>;

</script>


</head>
<body>

<p>Hisotgrama sobre probabilitats de sortir les paraules</p>


<div id="my_chart"></div>
     

</body>
</html>

histograma_ofc3.php

Aquestes dues gràfiques i mètodes vistos anteriorment els combino: ara tinc un fitxer que representa el formulari amb una combo a escollir entre una de les dues gràfiques; es fa una crida a un fitxer Javascript que implementa la funcionalitat AJAX; i independitzo les dades amb dos fitxers, un per cada gràfica.

histograma_ofc3.php

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="es" lang="es">

<head>
<title>Open Flash Chart amb AJAX i BD</title>
<script type="text/javascript" src="js/json/json2.js"></script>
<script type="text/javascript" src="js/swfobject.js"></script>
<script src="histograma_ofc3.js"></script>
</head>
<body>



<h2>Open Flash Chart + AJAX + Accés a BD</h2>
Probabilitat de sortir de les paraules del diccionari
<p>Escull la gràfica que vols mostrar</p>
<div>
<form name="form_ofc" method="post" >
<select name="grafica" onchange="mostraGrafica(this.value)">
	<option></option>
	<option value="1">grafica 1</option>
	<option value="2">grafica 2</option>
</select>
</form>
</div>
<br />
<div id="grafica"></div>

</body>
</html>

histograma_ofc3.js

var xmlHttp;
var data;

function mostraGrafica(vgrafica)
{
	xmlHttp=GetXmlHttpObject();
	if (xmlHttp==null)
	  {
	  alert ("Your browser does not support AJAX!");
	  return;
	}

	/*POST*/
	if (vgrafica==1) {
		var url="histograma_ofc3_dades1.php";
	} else if (vgrafica==2){
		var url="histograma_ofc3_dades2.php";	
	} else {
		return;
	}
	xmlHttp.open("POST", url, true);
	xmlHttp.onreadystatechange=function(){stateChanged_grafica();};
	xmlHttp.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
	xmlHttp.send();
}

function stateChanged_grafica() 
{ 
	
	if (xmlHttp.readyState==4) 
	{ 
			var oDiv=document.getElementById("grafica");
			cadena = xmlHttp.responseText;
			oDiv.innerHTML='<img src="img/ajax-loader.gif" alt="loading..." />';
			//alert(cadena);

				//To convert a JSON text into an object, you can use the eval() function. eval() invokes the JavaScript compiler. Since JSON is a proper subset of JavaScript, the compiler will correctly parse the text and produce an object structure. The text must be wrapped in parens to avoid tripping on an ambiguity in JavaScript's syntax.
				//http://www.json.org/js.html
				data = eval('(' + cadena + ')');
				//incrusto l'objecte flash
				swfobject.embedSWF("open-flash-chart.swf", "grafica", "250", "200", "9.0.0", "expressInstall.swf", {"get-data":"get_data"},{"loading":"loading..."},{"wmode":"transparent"} );
				//carreguem el gràfic
				get_data();

	}
	else 
	{ 
		document.getElementById("grafica").innerHTML='<img src="img/ajax-loader.gif" alt="loading..." />';
	}

}

/* ************** objecte GetXmlHttpObject *************************************************************************** */
function GetXmlHttpObject()
{
var xmlHttp=null;
try
  {
  /* Firefox, Opera 8.0+, Safari*/
  xmlHttp=new XMLHttpRequest();
  }
catch (e)
  {
  /* Internet Explorer*/
  try
    {
    xmlHttp=new ActiveXObject("Msxml2.XMLHTTP");
    }
  catch (e)
    {
    xmlHttp=new ActiveXObject("Microsoft.XMLHTTP");
    }
  }
return xmlHttp;
}

/* ************** Open Flash Chart ********************************************************************************************* */

function ofc_ready()
{
    //alert('ofc_ready');
}

function get_data()
{
	//alert(data); //el correcte és que surti [Object]. Hem de passar les dades JSON com a objecte
	return JSON.stringify(data);
}

function findSWF(movieName) {
  if (navigator.appName.indexOf("Microsoft")!= -1) {
    return window[movieName];
  } else {
    return document[movieName];
  }
}


histograma_ofc3_dades1.php

<?php
header ("Content-Type: text/html; charset=iso-8859-1");

include 'config_db.php';
include 'open_db.php';

$sql="select (round(probability/10))*10, count(*) from WORD group by round(probability/10) order by probability";
	
$rs = mysql_query($sql,$conn); 

$data_probability = array();
$data_count = array();
$y_max=0;

$rs = mysql_query($sql,$conn);
while( $row = mysql_fetch_array($rs) )
{
  $data_probability[] = $row[0];
  $data_count[] = floatval($row[1]);
  if ($y_max<$row[1]) $y_max=$row[1];
 }

include 'close_db.php';

//construim la gràfica
include 'php-ofc-library/open-flash-chart.php';

$title = new title( date("D M d Y") );

$bar = new bar();
//$bar->set_values( array(9,8,7,6,5,4,3,2,1) );
$bar->set_values( $data_count );

$chart = new open_flash_chart();
$chart->set_title( $title );
$chart->add_element( $bar );

$x_axis = new x_axis();
$x_labels = new x_axis_labels();
$x_labels->set_labels($data_probability);
$x_axis->set_labels( $x_labels);
$chart->set_x_axis($x_axis);
	
$y_axis = new y_axis(); 
$y_axis->set_range(0,$y_max,10);
$chart->set_y_axis( $y_axis );

//enviem les dades JSON al Javascript
echo $chart->toPrettyString();

?>

histograma_ofc3_dades2.php

<?php
header ("Content-Type: text/html; charset=iso-8859-1");

include 'config_db.php';
include 'open_db.php';

$sql="select probability from WORD order by probability";
$rs = mysql_query($sql,$conn); 

$data_count = array();

$rs = mysql_query($sql,$conn);
while( $row = mysql_fetch_array($rs) )
{
  //$data_probability[] = $row[0];
  //$data_count[] = floatval($row[1]);
  switch (intval ($row[0] / 10)+1) {
    case 1:
        $data_count[0]++;
        break;  
    case 2:
        $data_count[1]++;
        break;  
    case 3:
        $data_count[2]++;
        break;  
    case 4:
        $data_count[3]++;
        break;  
    case 5:
        $data_count[4]++;
        break;  
    case 6:
        $data_count[5]++;
        break;  
    case 7:
        $data_count[6]++;
        break;  
    case 8:
        $data_count[7]++;
        break;  
    case 9:
        $data_count[8]++;
        break;  
    case 10:
        $data_count[9]++;
        break; 
}

  //if ($y_max<$row[1]) $y_max=$row[1];
 }

$y_max=0;
//for ($valorActual in $data_count) { 
foreach($data_count as $key=>$value){
  if ($value>$y_max) {$y_max=$value;}
}

//print_r($data_count);

include 'close_db.php';

//construim la gràfica
include 'php-ofc-library/open-flash-chart.php';

$title = new title( date("D M d Y") );

$bar = new bar_glass();
//$bar->set_values( array(10,9,8,7,6,5,4,3,2,1) );
$bar->set_values( $data_count );

$chart = new open_flash_chart();
$chart->set_title( $title );
$chart->add_element( $bar );

$x_axis = new x_axis();
$x_labels = new x_axis_labels();
$x_labels->set_labels(array("10","20","30","40","50","60","70","80","90","100")); //els labels han de ser char
$x_axis->set_labels( $x_labels);
$chart->set_x_axis($x_axis);
	
$y_axis = new y_axis(); 
$y_axis->set_range(0,$y_max,10);
$chart->set_y_axis( $y_axis );

//enviem les dades JSON al Javascript
echo $chart->toPrettyString();
?>

creat per Joan Quintana Compte, març 2009

Eines de l'usuari
Espais de noms
Variants
Accions
Navegació
IES Jaume Balmes
Màquines recreatives
CNC
Informàtica musical
joanillo.org Planet
Eines