Hi everyone,

I'm sure there are people who are using highCharts framework. I'm having a trouble passing the values to jquery code from PHP json. Your help is so appreciated.

This is my php section

<?php
        header('Cache-Control: no-cache, must-revalidate');
        header('Expires: Mon, 01 Jan 2013 00:00:00 GMT');

        // The JSON standard MIME header.
        header('Content-type: text/json');



        include('mysql_connector.php');
        $port = new MySqlDatabase();
        $port->connect('root','','theants');


        $query = "select * from userss";
        $result = mysql_query($query);


        $array = mysql_fetch_assoc($result);
        $jsonData = json_encode($array);

        echo $jsonData;

?>

This is my jquery section

$.getJSON('ajax.php', function(jsonData){

                                    $.each(jsonData, function(key, value){

                                        chart = new Highcharts.Chart({
                                            chart: {
                                                renderTo: 'container',
                                                type: 'pie'
                                            },
                                            title: {
                                                text: 'User Ages'
                                            },
                                            xAxis: {
                                                categories: ['0-9', '10-19', '20-29', '30-39', '40-49', '50-59', '60-69', '70-79'],
                                                title: {
                                                    text: 'Age group'
                                                }
                                            },

                                            tooltip: {
                                                formatter: function() {
                                                    return ''+
                                                        this.series.name +': '+ this.y +' user(s)';
                                                }
                                            },
                                            plotOptions: {
                                                bar: {
                                                    dataLabels: {
                                                        enabled: true
                                                    }
                                                }
                                            },
                                            legend: {
                                                layout: 'vertical',
                                                align: 'right',
                                                verticalAlign: 'top',
                                                x: -100,
                                                y: 100,
                                                floating: true,
                                                borderWidth: 1,
                                                backgroundColor: '#FFFFFF',
                                                shadow: true
                                            },

                                            series: [{
                                                name: 'No. of Users',
                                                data: []
                                            }]
                                        });


                                    });
                            }

            );

I just want to get the values from the function "function(key,value)" and I am not concerned about the key. Quick example/examples will do for now.

The second demo in the HighCharts demo gallery shows the flow you need.

a link will do, man. I'm trying to get the values using ajax or getJSON methods in jquery but nothing works for me or probably not sure how to use them right.

My first posty wasn't meant to tell you I'm using highstock charts. In facts, I'm using a highcharts pie chart which I couldn't pass the live data to. Here is the actual code. I'm fiddling with the examples given on their website.

function getData(){
            $.ajax({
                   url:'ajax.php',
                   success: function(data){

                                var series = chart.series[0],
                                    shift = series.data.length > 20;

                                     chart.series[0].addPoint(data, true, shift);

                                    // call it again after one second
                                    setTimeout(getData, 1000);    


                   },
                     cache: false  

            });
        }
                var chart;
                $(document).ready(function() {

                    chart = new Highcharts.Chart({
                        chart: {
                            renderTo: 'container',
                            plotBackgroundColor: null,
                            plotBorderWidth: null,
                            plotShadow: false
                        },
                        title: {
                            text: 'Number of users per game'
                        },
                        tooltip: {
                            pointFormat: '{series.name}: <b>{point.percentage}%</b>',
                            percentageDecimals: 1
                        },
                        plotOptions: {
                            pie: {
                                allowPointSelect: true,
                                cursor: 'pointer',
                                dataLabels: {
                                    enabled: true,
                                    color: '#000000',
                                    connectorColor: '#000000',
                                    formatter: function() {
                                        return '<b>'+ this.point.name +'</b>: '+ this.percentage +' %';
                                    }
                                }
                            }
                        },
                        series: [{
                            type: 'pie',
                            name: 'Browser share',
                            data: [
                                ['Firefox',   45.0],
                                ['IE',       26.8],
                                {
                                    name: 'Chrome',
                                    y: 12.8,
                                    sliced: true,
                                    selected: true
                                },
                                ['Safari',    8.5],
                                ['Opera',     6.2],
                                ['Others',   0.7]
                            ]
                        }]
                    });


                }); 

I'd appreciate the help if someone has used them and would be happy to show how to extract the JSON data into jquery and let the graph generator make a graph based on the data passed to it. I feel like I ain't making much use of their API's.

Something like this ?

thumbs up to both of you! i had taken a look at highcharts way back, but was unable to really get it to work with regard to pulling data from a database. You inspired me and I finally set some time aside to figure out how to pull data from SQL, write the output as JSON (from an ASP.NET page), and push the series values to the highchart.

So thanks again for the thread!

I had a look at the example you mentioned here. And also, I tried passing the data to series like shown in the example but nothing worked. I'm getting sick of workin out how the highcharts takes data. Please anyone here keen to help?

Can anyone help with the charts? I'm so desparate.

Forgot about this... Had silently hoped JorgeM would've posted his findings. If I find the time I'll look into it.

Sorry, didn't post my findings because the scenario is a bit different. In any event, maybe this will help you or someone else with a similar situation. What I was able to get working was building a standard bar chart from JSON data (coming from an asp.net/vb page).

Here is the code I used in my asp.net page which pulls information from a SQL data source, outputs the results in a JSON format. Just fill in the SQL connection and query information, uncomment the lines and remove the line that I have below just providing static data. Build the JSON sytnax using "objJSONSB.Append"

 Dim objSQLConn As SqlConnection
 Dim objSQLCmd As SqlCommand
 Dim objSQLDataReader As SqlDataReader
 Dim objJSONSB As StringBuilder

 Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs)
   Response.Clear()
   Response.ContentType = "application/json"
   Response.Write(getJSON())
   Response.End()
 End Sub

 Function getJSON() As String
   objJSONSB = New StringBuilder()
   'objSQLConn = New SqlConnection(System.Configuration.ConfigurationManager.AppSettings("connString"))
   'objSQLCmd = New SqlCommand("sql query goes here", objSQLConn)

   'objJSONSB.Append("[")
   'objSQLCmd.Connection.Open()
   'objSQLDataReader = objSQLCmd.ExecuteReader()

   'While objSQLDataReader.Read()
     'objJSONSB.Append("{")
     'objJSONSB.Append("""col1""")
     'objJSONSB.Append(":")
     'objJSONSB.Append("""" & objSQLDataReader("col1") & """")
     '
     ' Just continue building the JSON data, to follow the format of the next line...
     '
  'End While

  'objSQLDataReader.Close()
  'objSQLCmd.Connection.Close()

  'objJSONStringBuilder.Remove(objJSONStringBuilder.Length - 1, 1)
  'objJSONStringBuilder.Append("]")

  ' The following line is just static test data.  Remove it after testing...
  objJSONSB.Append("[{""name"": ""Jane"", ""data"": [1,0,4]},{""name"": ""John"",""data"": [5,7,3]}]")

 Return objJSONSB.ToString
End Function

Next, my javascript code which pulls this information and builds the bar chart.

<!DOCTYPE html>
<html>
<head>
    <title>HighCharts Example</title>
    <script src="..URL to jQuery File.." type="text/javascript"></script>
<script src="highcharts.js" type="text/javascript"></script>
<script type="text/javascript">
        var chart;
        $(document).ready(function () {
            options = {
                chart: {
                    renderTo: 'container',
                    type: 'bar'
                },
                title: {
                    text: 'Academic Scores'
                },
                xAxis: {
                    categories: ['Math', 'Science', 'History']
                },
                yAxis: {
                    title: {
                        text: 'Scores'
                    }
                },
                series: []
            };

            $.getJSON('http://URL_to_ASPX_Page', function (data) {
                options.series = data;
                chart = new Highcharts.Chart(options);
            });
        });

</script>
</head>
<body>
    <div id="container" style="min-width: 400px; height: 400px; margin: 0 auto"></div>
</body>
</html>

is that how it's normally configured? I thought you'd have a for-loop in the JavaScript code to loop through the data you're getting from the DB.

In this case, I've looped through the data that I pulled from the data source and built the JSON string. From my understanding, the technique I tried is not necessarily the most optimal, but just as you, i encountered a challange with this.

The aspx page outputs the JSON string and the Ajax call takes this return value and assigns it to options.series.

With my script, I could call the decode_json function in php which basically takes an array and converts to JSON format. I was able to get the data passed to AJAX function in my JS. Although, the series object in highcharts didn't make sense so I didn't know how to pass the data to it.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.