0

I have a PHP array with this content:

[{"label":"Baden-Wuerttemberg","year":"1998","ins":"243812"}...] (34 entries).

Now I want to plot a chart with Chart.js in JS, but I don't know how to get the values for Labels and dataset.

This is what I have tried:

var jsArray = <?php echo json_encode($jsonArray); ?>;

    var chart = new CanvasJS.Chart("chartContainer", {
        title: {
            text: "My First Chart in CanvasJS"
        },
        type: 'line',
        data: {
            datasets: jsArray
        },

    });
    chart.render();
}

I want to plot on the x axis the year Jahr and on the y axis the total number ins.

3
  • It's best to use AJAX for PHP <-> JavaScript communication. Commented May 29, 2017 at 20:55
  • Have you tried : JSON.parse('<?=$jsonArray;?>? - The example you provided, is already json encoded, just pass it to js. When you ask a question about an error ALWAYS include the error log. Add error_reporting(E_ALL); ini_set('display_errors', 1); at the top of your php script, what does it return? Commented May 29, 2017 at 21:04
  • nothing mate, still an empty screen. I tried it with JSON.parse('<?=$jsonArray;?> and the error reporting. Commented May 29, 2017 at 21:11

1 Answer 1

3

json_encode function returns json encoded string but in the chart.js you would need json object. You just need to parse the string to object in javascript part like this:

var jsArray = JSON.parse('<?php echo json_encode($jsonArray); ?>');

That should work!


Update

According to Chart.js documentation, each single object in dataPoints can have following properties:

{
    "label": "string, will appear if hovered the bar",
    "x": 10, // must be a number
    "y": 20 // must be a number
}

So you need to convert your data to have above format, something like this:

$formattedData = [];
foreach( $jsonArray as $data ) {
    $formattedData[] = [
        "label" => $data->Bundesland,
        "x"     => (int) $data->label,
        "y"     => (int) $data->sum
    ];
}

Then finally use the $formattedData like this:

var jsArray = JSON.parse('<?php echo json_encode($formattedData); ?>');

There is no other problem in js part, only problem was the format of data.

Sign up to request clarification or add additional context in comments.

7 Comments

Dont work, i get an empty screen. Here ist my code: (paste.ofcode.org/P2GULiw4WGAQHt2D8fkmx6)
You have a typo type: type, value should be a string. Here is a working example: jsfiddle.net/7vgLmkoc/3
i changed it to line but still empty screen. I have in my array 3 values as u can see in my post.
What is the type of your $jsonArray variable?
its an json object or not?
|

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.