0

I try a little with dygraph. I get my data from an ajax call and I need to convert my returned JSON array to a JavaScript array.

Now my dygraph options look like this

    series = {
      sample1: {
        color: 'Green',
        strokeWidth: 3,
        pointSize: 4
      },
      sample2: {
        color: 'DarkBlue',
        strokeWidth: 2,
        pointSize: 3
      },
      sample3: {
        color: 'DarkOrange',
        strokeWidth: 1,
        pointSize: 2
      }
    }

   dygraph_options = {
      title: title,
      labels: jsonDataTable.labels,
      series: series,
      ...
   }

My php ajax call look like this:

$series = array();
$series[] = array( 'sample1' => array('color' => 'Green'));
$series[] = array( 'sample2' => array('color' => 'DarkBlue'));
$series[] = array( 'sample3' => array('color' => 'DarkOrange'));

$table = array( "series" => $series, "labels" => $labels, "data" => $rows );
return $table;

I want to get the series from json. But my returned series are different from the javascript series:

jsonDataTable.series -> [Object { stock={...}}, Object { forecast={...}}]
javascript series -> Object { stock={...}, forecast={...}, training={...}}

I try a lot but can't get it working.

2 Answers 2

1

You want $series to be an associative array:

$series = array();
$series['sample1'] = array('color' => 'Green');
$series['sample2'] = array('color' => 'DarkBlue');
$series['sample3'] = array('color' => 'DarkOrange');

Or

$series = array(
   'sample1' => array('color' => 'Green'),
   'sample2' => array('color' => 'DarkBlue'),
   'sample3' => array('color' => 'DarkOrange')
);
1
  • Oh my got the associative array is exactly what I want and it is soo easy, why did not I try this??? Thank You! Commented Jan 21, 2017 at 14:46
1

Prepare array to send from php to javascript:

echo json_encode( $array );

Translate the data in javascript to a nice object

var a = JSON.parse( phpdata );

Prep to send data to php from javascript

var tosend = JSON.stringify( a );

Translate incoming js object back into php

$a = json_decode( $some_json );

or

$a = json_decode( $some_json, true );

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.