Charts and graphs with jplot, jQuery and php

For rendering charts in one of my projects, I started using jplot library.

Usage is pretty simple, but I needed some specifics in implementation.
First, add the following lines to HEAD section:


In my case, I used also date rendering and some more features, provided by jplot.

Then I added the following code to my page:

I used such construction in order to dynamically return reports on needed options.

My javascript code is following:

$(function() {
var plot2 = "";

    $('select#price').change(function() {
        if (plot2) plot2.destroy(); //this string is needed to make sure, that old chart is not displayed while new is generated
        var id = $(this).val(); // here we get selected option value
        var name = $("#price option[value='" + id + "']").text(); // here we take the name of option, selected.

        $.getJSON("/lib/helpers/price_data.php?price_code=" + id, //read JSON data from helper script
            function (data) {
                plot2 = $.jqplot('chart_display', [data], {
                    title: name,
                            renderer:$.jqplot.DateAxisRenderer, // X axis will be rendered as date
                                formatString: '%b %#d' // format of date display
                                formatString:'%.2f EUR' // format of price display
                        {lineWidth:4, markerOptions:{style:'square'}} // one of the features to display break points
                    highlighter: {
                        show: true // mouse hover highlighting on break points
                    cursor: {
                        show: false,
                        tooltipLocation:'sw' // mouse hover tooltip onbreak points

To display correctly all these data, we need correct data to be returned by our php script. In my case it should be in format of JSON data [[‘2008-09-30 4:00PM’,4], [‘2008-10-30 4:00PM’,6.5], [‘2008-11-30 4:00PM’,5.7], [‘2008-12-30 4:00PM’,9], [‘2009-01-30 4:00PM’,8.2]]

For this purpose, I generate output of script in the following way:

$query = mysql_query("SELECT * FROM prices WHERE price_code = '$price_code' ORDER BY date") or die(mysql_error());
while ($row = mysql_fetch_array($query))
     $result[] = array($row['date'].' 0:00AM', round($row['price']));
print json_encode($result);

Leave a Reply

%d bloggers like this: