Using Custom Javascript

For more advanced usage, properties such as data renderer, can have user defined custom javascript function as the event handler. In order to reference a javascript function on client side, you must prefix “js::” before the function name, so the phpChart knows it’s a custom javascript function.

1
2
// ajaxDataRenderer is a javascript function defined by user
$pc->set_data_renderer('js::ajaxDataRenderer');

The examples below use custom javascript as the data source for the data renderer. This is extremely useful in situation where the data is dynamically or conditionally created.

In addition, the second example also demonstrates using a data source from a URL using Ajax for plotting series on a PHP graph. In the example it passes URL jsondata.txt as the data source, which can be replaced with any URL provisioning data in valid JSON format.

Documentation on set_data_renderer() method used in the examle can be found here.

complete code:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
<?php
require_once("../conf.php");
?>
<!DOCTYPE HTML>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>phpChart - Basic Chart with Custom Javascript</title>
</head>
 
<body>
<style type="text/css">
#basic_chart_4 .jqplot-point-label {
 border: 1.5px solid #aaaaaa;
 padding: 1px 3px;
  background-color: #eeccdd;
}
</style>
<?php
$data1 = array();
$pc = new C_PhpChartX(array($data1),'basic_chart_4');
$pc->set_title(array('text'=>'Basic Chart with Custom JS'));
$pc->set_data_renderer("js::sineRenderer");
$pc->add_plugins(array('pointLabels'));
$pc->set_animate(true);
$pc->draw();
?>
<script>
sineRenderer = function() {
    var data = [[]];
    for (var i=0; i<13; i+=0.5) {
      data[0].push([i, Math.sin(i)]);
    }
    return data;
  };
</script>

<?php
$data1 = array();
$pc = new C_PhpChartX('./jsondata.txt','basic_chart_ajax');
$pc->set_title(array('text'=>'Basic Chart with Ajax'));
$pc->set_data_renderer("js::ajaxDataRenderer");
$pc->draw();
?>
<script>
var ajaxDataRenderer = function(url, plot)
        {
            var ret = null;
            $.ajax({
                // have to use synchronous here, else returns before data is fetched
                async: false,
                url: url,
                dataType:'json',
                success: function(data) {
                    ret = data;
                }
            });
            return ret;
        };
</script>
</body>
</html>

Live demo (scroll down to see the 2nd example)

No related content found.

Tags: ,

Top

Clicky