blank page highchart in using jquery to call json arrary

泪湿孤枕 提交于 2019-12-18 09:37:54

问题


I have a php page (array.php). On the browser, array.php produces the ff result

[{"name":"London","data2":["70","19"]},{"name":"Tokyo","data2":["60","18"]}]

array.php page

<?php
//header("Content-type: text/json");
header("Content-type: application/json");


$db = mysql_connect("localhost", "username", "userpasswd"); 
mysql_select_db("weather",$db);
$query = "SELECT * FROM measures";

$result = mysql_query($query,$db);

while($row = mysql_fetch_array($result))
{
$h = $row["humidity"];
$w = $row["windspeed"];
$t = $row["temperature"];
$c = $row["city"];
$ar1[] = array("name" =>$c,"data2"=>[$h,$t]);
}
echo json_encode($ar1);

?>

The code of the jquery page is

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"     "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
<script src="./js/highcharts.js"></script>

<script type="text/javascript">

var chart = null;      // global
$(document).ready(function() {
chart = new Highcharts.Chart({
    chart: {
        renderTo: 'container',
        defaultSeriesType: 'column',
        events: {
            load: requestData
        }
    },
    title: {
        text: 'Real time data from database'
    },
    xAxis: {
            categories: []
        },
    yAxis: {
        minPadding: 0.2,
        maxPadding: 0.2,
        title: {
            text: 'Value',
            margin: 80
        }
    },
    series: []
});        
});

/**
 * Request data from the server
 */
function requestData() {

$.ajax({
    url: 'array.php',
    success: function(point) {

    $.each(point, function(i,item){
        var series_name = item.name;
        var series_data = item.data2;

        var series = {data: []};

        chart.xAxis.categories.push(series_name);
        //chart.series.data.push(item.data2);

        $('body').append( "Name: " + series_name);
        alert(series_data);

    });


    },
    cache: false
});
}

</script>

</head>

<body>

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

The code is not complete though. but until the error is fixed I can't move forward. If I run the html code, the alert function works well by looping through and alerting each of the data from the array.php. But if I uncomment

//chart.xAxis.categories.push(series_name); or //chart.series.data.push(item.data2);

then the alert function doesn't work any more. I have a feeling that it doesn't recognize the variable (chart). I have declared it before

$(document).ready(function() { 

so that it will be a global variable but it doesn't seem to be so.

Please, I truly need help. I being working on this for days now but no success. I will deeply appreciate it. Thanks in advance - Emma


回答1:


Do you really need to make an Ajax call? Can you not push the data during the page processing in php? I don't see you doing any loop or real time updates to the chart, you are just trying to load data at load, instead of Ajax, I would recommend direct php.

As far as your problem goes, yes chart is not instantiated at the time that you are trying to access it. I tried to reproduce your issue @ http://jsfiddle.net/jugal/Zjket/ Following are my findings

The requestData method is called during the call to Highchart's constructor. So? This means the constructor call isn't complete yet, and hence the object (chart) has not been instantiated yet. Highchart also supports having a callback method as a second param to its constructor, which it calls after construction (but still from the constructor, just that your chart is ready now, internally, but the constructor call has not yet returned to its caller) as chart = new Highcharts.Chart({...},requestData) but same problem persists. Strange? Not really, the requestData method gets called with the chart object as its context, this means that though you cannot refer to the "chart" using the chart variable, you can access it with this as the chart is the caller to requestData.

Unfortunately your problem just reaches the next level now, but the chart still wont show data, as now the new error being, your json is formatted incorrect [{"name":"London","data2":["70","19"]},{"name":"Tokyo","data2":["60","18"]}], the numbers shouldn't be inside quotes, it should instead be [{"name":"London","data2":[70,19]},{"name":"Tokyo","data2":[60,18]}] you will need to convert the values to numbers before you pass them to json_encode. Few more errors were encountered after fixing this. Also, you are not really supposed to push series to the chart.series object, instead use chart.addSeries(...) @ http://www.highcharts.com/stock/ref/#series

Some more fiddling around and debugging brought me to this solution http://jsfiddle.net/jugal/JfgxX/

 function requestData() {
 chart=this;
 $.ajax({
url: 'array.php',
success: function(point) {
    $.each(point, function(i,item){
    var series_name = item.name;
    var series_data = item.data2;
    var series = {data: item.data2,name:series_name};
    chart.addSeries(series);
});


},
cache: false
});
  }

EDIT Another alternative to your approach can be, like @wergeld mentioned, to make the Ajax call first and then create the chart on success of that call, as follows. fiddle @ http://jsfiddle.net/jugal/j4ZYB/

 var chart=null;
$(function() {
   requestData();
});

function requestData() {
     $.ajax({
    url: 'array.php',
     success: function(point) {
      var chartSeriesData=[];
         $.each(point, function(i,item){
         var series_name = item.name;
         var series_data = item.data2;     
         var series = {data: item.data2,name:series_name};
        chartSeriesData.push(series);
        });
     chart = new Highcharts.Chart({
    chart: {
        renderTo: 'container',
        defaultSeriesType: 'column'      ,      

    },
    title: {
        text: 'Real time data from database'
    },
    xAxis: {
            categories: []
        },
    yAxis: {
        minPadding: 0.2,
        maxPadding: 0.2,
        title: {
            text: 'Value',
            margin: 80
        }
    },
    series: chartSeriesData
});         
},
cache: false
});
  }

}



回答2:


Looks like you are trying to push the data to the chart before it has been created. You are declaring the chart as NULL, yes, but how is the chart var going to know it is supposed to have data pushed to it when it does not know what it is? Seems like the order of your page execution is:

  1. declare chart
  2. get data via ajax
  3. push data to chart
  4. declare chart as Highcharts.Chart

Why not get you data from your ajax call and then inside the $(document).ready(function() { call the push to the chart of the data. This way your order of operation would be:

  1. get data via ajax
  2. declare chart as Highcharts.Chart
  3. push data to chart


来源:https://stackoverflow.com/questions/11851122/blank-page-highchart-in-using-jquery-to-call-json-arrary

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!