Using Highcharts with PHP and JSON Data in JavaScript

I’m trying to generate a chart using individual data points. It seems like a simple task, yet I’ve spent two days struggling to find a solution. Here’s my PHP code snippet:

for ($j = 0; $j < $totalResults; $j++) {
    $record = $resultSet->fetch_assoc();
    array_push($outputArray, array($record['weekNumber'] => $record['powerValue']));
}
echo json_encode($outputArray);

The output generated by the PHP is: [{"1":"51"},{"2":"52"},{"3":"52"}]

My corresponding JavaScript code looks like this:

$.getJSON('fetchPower.php', function(data) {
    var dataSeries = {};
    $.each(data, function(index, item) {
        dataSeries.data = item;
        chartOptions.series.push(dataSeries);
    });
    var myChart = new Highcharts.Chart(chartOptions);
});

Despite this setup, the graph is not being rendered. I would appreciate any guidance.

To properly render your Highcharts chart with the JSON data from your PHP script, you need to slightly adjust how the data is being formatted and parsed in JavaScript. The current PHP output is an array of objects, but Highcharts expects a specific format for its data series.

Here's how you can modify your setup for better efficiency and results:

PHP Code

Refactor your PHP code to return data in the form of an array instead of objects. This adjustment simplifies the parsing process on the JavaScript side and aligns with Highcharts' expectations:

for ($j = 0; $j < $totalResults; $j++) {
    $record = $resultSet->fetch_assoc();
    // Modify to use numeric indices
    $outputArray[] = [(int)$record['weekNumber'], (int)$record['powerValue']];
}
echo json_encode($outputArray);

JavaScript Code

Update your JavaScript to match the expected format. Rather than creating individual series for each object, your data should be a single series array:

$.getJSON('fetchPower.php', function(data) {
    var chartOptions = {
        chart: {
            renderTo: 'container', // Ensure this matches your HTML container's ID
            type: 'line'
        },
        series: [{
            data: data  // Directly assign the data array
        }]
    };
    var myChart = new Highcharts.Chart(chartOptions);
});

By aligning your PHP output format with the data structure expected by Highcharts, you should see your chart displayed correctly. This method also helps in maintaining clarity and optimizing the data processing workflow on both the backend and frontend sides.

It looks like you've provided a solid foundation for your project, but to better utilize Highcharts with PHP and JSON data, let's explore another way to structure both your PHP output and JavaScript logic.

PHP Code

Instead of generating multiple objects, you might find it more convenient to format your output as a list of key-value pairs, where keys are your week numbers and values are the power values:

$outputArray = [];
for ($j = 0; $j < $totalResults; $j++) {
    $record = $resultSet->fetch_assoc();
    $outputArray[(int)$record['weekNumber']] = (int)$record['powerValue'];
}
echo json_encode($outputArray);

This structure outputs something like:

[1 => 51, 2 => 52, 3 => 52]

JavaScript Code

In your JavaScript logic, you should parse this key-value object into a simple array of arrays, which Highcharts can consume:

$.getJSON('fetchPower.php', function(data) {
    var dataSeries = [];
    // Convert the object into an array of arrays
    $.each(data, function(week, power) {
        dataSeries.push([parseInt(week), power]);
    });

    // Initialize Highcharts
    var chartOptions = {
        chart: {
            renderTo: 'container',
            type: 'line'
        },
        series: [{
            data: dataSeries
        }]
    };
    var myChart = new Highcharts.Chart(chartOptions);
});

In this setup, your PHP script outputs a more streamlined JSON, and the JavaScript processes it into a format that Highcharts can directly interpret as series data. This alternative method can help ensure that data handling and chart rendering processes are seamlessly integrated.