Vous pouvez utiliser du code côté serveur pour acquérir des données afin de remplir votre graphique. Votre code côté serveur peut charger un fichier local, interroger une base de données ou récupérer les données d'une autre façon. L'exemple PHP suivant illustre la lecture de données de graphique à partir d'un fichier texte local lorsqu'une page est demandée. Vous pouvez copier ces fichiers sur votre propre serveur, s'il est compatible avec PHP.
Remarque:Cet exemple nécessite jQuery 1.6.2 ou version ultérieure.
exampleUsingPHP.html fichier
Il s'agit du fichier que l'utilisateur consulte. La fonction "drawChart()" appelle la fonction jQuery ajax() pour envoyer une requête à une URL et obtenir une chaîne JSON. L'URL ici correspond au fichier local getData.php. Les données renvoyées sont en fait des DataTable
définies dans le fichier local sampleData.json. Ce paramètre DataTable
permet de remplir un graphique à secteurs, qui est ensuite affiché sur la page.
<html> <head> <!--Load the AJAX API--> <script type="text/javascript" src="https://www.gstatic.com/charts/loader.js"></script> <script type="text/javascript" src="//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script> <script type="text/javascript"> // Load the Visualization API and the piechart package. google.charts.load('current', {'packages':['corechart']}); // Set a callback to run when the Google Visualization API is loaded. google.charts.setOnLoadCallback(drawChart); function drawChart() { var jsonData = $.ajax({ url: "getData.php", dataType: "json", async: false }).responseText; // Create our data table out of JSON data loaded from server. var data = new google.visualization.DataTable(jsonData); // Instantiate and draw our chart, passing in some options. var chart = new google.visualization.PieChart(document.getElementById('chart_div')); chart.draw(data, {width: 400, height: 240}); } </script> </head> <body> <!--Div that will hold the pie chart--> <div id="chart_div"></div> </body> </html>
Fichier getData.php
Lorsque ce fichier reçoit une requête, il renvoie une copie du fichier local sampleData.json.
<?php // This is just an example of reading server side data and sending it to the client. // It reads a json formatted text file and outputs it. $string = file_get_contents("sampleData.json"); echo $string; // Instead you can query your database and parse into JSON etc etc ?>
Fichier sampleData.json
Une version JSON d'un petit fichier DataTable
.
{ "cols": [ {"id":"","label":"Topping","pattern":"","type":"string"}, {"id":"","label":"Slices","pattern":"","type":"number"} ], "rows": [ {"c":[{"v":"Mushrooms","f":null},{"v":3,"f":null}]}, {"c":[{"v":"Onions","f":null},{"v":1,"f":null}]}, {"c":[{"v":"Olives","f":null},{"v":1,"f":null}]}, {"c":[{"v":"Zucchini","f":null},{"v":1,"f":null}]}, {"c":[{"v":"Pepperoni","f":null},{"v":2,"f":null}]} ] }
Informations complémentaires :