JSON for jqPlot
Asked Answered
D

4

6

I would like to use jqPlot usinge data from server side coming in JSON, like described in this example: http://www.jqplot.com/tests/data-renderers.php

My code is nearly the same like the example:

function myGraph(jsonurl) {

  var ajaxDataRenderer = function(url, plot, options) {
    var ret = null;
    $.ajax({
      // have to use synchronous here, else the function
      // will return before the data is fetched
      async: false,
      url: url,
      dataType:"json",
      success: function(data) {
        ret=data;
        console.warn(data);
      }
    });
    return ret;
  };



var plot1 = $.jqplot('chartdiv', jsonurl, {
      title: 'myTitle',
      dataRenderer: ajaxDataRenderer,
      dataRendererOptions: {  unusedOptionalUrl: jsonurl    },
      series: [{
          label: 'myLabel',
          neighborThreshold: -1
      }],
      axes: {
          xaxis: {
              renderer: $.jqplot.DateAxisRenderer,
            //  min:'August 1, 2010 16:00:00',
              tickInterval: '2 months',
              tickOptions:{formatString:'%Y-%m-%d.%H:%M:%S'}
          },
          yaxis: {
              tickOptions:{formatString:'$%.2f'}
          }
      },
  });

On server side i'm using PHP (and Yii). The webpage returns an array, which is encoded to JSON by using CJSON::encode($resultArray); (this Yii function passed trough to the PHP JSON encode function). The Results from the PHP script lookes like that:

{"2011-04-25 14:46:40":2,"2011-04-26 14:46:40":3,"2011-04-27 14:46:40":5}

The Ajax request on client side resolved something like this (output from console.info(); )

Object { 2011-04-25 14:46:40=2,  2011-04-26 14:46:40=3, ...}

Probably, jqPlot expect the following format:

[[["2011-04-25 14:46:40":0],["2011-04-26 14:46:40",3],["2011-04-27 14:46:40",0]]]

All the time i get the error uncaught exception: [object Object] What is wrong? Is there a way to convert the object for to the typical array form?

Thank you

Diffuse answered 14/7, 2011 at 13:3 Comment(0)
D
4

I have something like this . I had 2 arrays for values,labels .You should construct string as below from arrays .

        $size = count($labels);

        for ($i = 0; $i < $size; $i++) {
            $result = $result . "['" . $labels[$i] . "'," . $values[$i] . "]";
            if($i != $size -1 ){
                $result = $result . ",";
            }
        }

OR if you dont have 2 arrays and just have this string {"2011-04-25 14:46:40":2,"2011-04-26 14:46:40":3,"2011-04-27 14:46:40":5} you can replace { with [ , } with ] and , with ],[ . A dirty but quick solution .

After above code you might need to append '[' and ']' on both sides and return value.

Danette answered 14/7, 2011 at 13:7 Comment(2)
I think, building an string on PHP side which looks like an JS array is more an workaround. But it's the onlyest way, which work. By the way, I have to "parse" the string on client side with eval. Which means: resultArray=eval(data)Diffuse
It's very silly to a beginner, but jqPlot expects its data in [[val1, val2, val3]] format. Thanks for the hint here.Farfetched
R
4

Do not parse the result on the client side, jquery will do much better. Actually, the array you need for jqplot is in fact valid json. All you have to do is prepare your data and create the appropriate array structure in PHP:

$pairs = array(1=>2, 3=>5, 4=>7, 5=>12, 7=>23); // simple example

$result = array();

foreach ($pairs as $label => $value) {
    $result[] = array($label,$value); // make a "small" array for each pair
}

echo json_encode(array($result)); // wrap the result into another array; multiple plot data go like "array($result, $result2, ...)"

The result looks like this:

[[[1,2],[3,5],[4,7],[5,12],[7,23]]] 

and is excatly what you need.

Ramiform answered 26/2, 2012 at 11:23 Comment(0)
L
1

From http://www.jqplot.com/tests/date-axes.php

Note, although jqPlot will parse most any human readable date, it is safest to use javascript time stamps when possible. Also, it is best to specify a date and time and not just a date alone. This is due to inconsistent browser handling of local time vs. UTC with bare dates.

And example data from site:

var line1=[['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]];

So you need array filled with 2 element arrays. First string with date (use timestamp if can) and X value. I've tried to find input format for datetime parsing or something like that but with no result.

You generated

{"2011-04-25 14:46:40":2,"2011-04-26 14:46:40":3,"2011-04-27 14:46:40":5}

which is object with 3 fields. First field name is "2011-04-25 14:46:40" and it's value set to 2. You need to generate array like this:

[["2011-04-25 14:46:40", 0],["2011-04-26 14:46:40", 3],["2011-04-27 14:46:40", 0]]

JSFiddle with your data seems to work - so don't need timestamps ;) http://jsfiddle.net/zpygcvps/1/

Longitudinal answered 22/10, 2014 at 11:51 Comment(0)
D
0

sine curve with PHP json_encode function

server side

<?php

    $y = array();

    $index = 0 ;
    for($x = 0 ; $x< 13 ; $x += 0.5) {
        $y[$index] =  sin($x);
        $index++ ;
    }

    $series = array();
    $series[0] = $y ;
    $data = json_encode($series);
    echo $data;

?>

client side

<script type="text/javascript">
        $(document).ready(function(){

            var ajaxDataRenderer = function(url, plot, options) {
            var ret = null;
            $.ajax({
              async: false,
              url: url,
              dataType:"json",
              success: function(data) {
                ret = data;
              }
            });
            return ret;
          };

        // The url for our json data
        var jsonurl = "/test/chart/jqplot-data.php";

        var plot2 = $.jqplot('chartdiv', jsonurl,{
            title: "AJAX JSON Data Renderer",
            dataRenderer: ajaxDataRenderer,
            dataRendererOptions: {
              unusedOptionalUrl: jsonurl
            }
          });

        });
    </script>
Deathday answered 27/8, 2012 at 12:55 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.