使用ajax和php在下拉列表中动态更新谷歌图表

时间:2012-10-27 12:58:07

标签: php ajax drop-down-menu google-visualization

我必须根据下拉值显示谷歌图表,其中包含商店ID 我正在从mysql中检索数据,没有值的问题,我正在根据ajax的商店ID检索数据,只是在输入框中确认它也没关系。

但我不知道如何使用这些值更新该图表,而无需重新加载页面。 这是我的谷歌图表代码与硬编码值。

 <!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>
    <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
    <title>newChart</title>
    <script type="text/javascript" src="https://www.google.com/jsapi"></script>
        <script type="text/javascript"> 
          google.load("visualization", "1", {packages:["corechart"]});
          google.setOnLoadCallback(drawChart);
          function drawChart()
          {var data = google.visualization.arrayToDataTable([['Company & Model', 'Views'],['Samsung Hero Music E1232B',5],['Samsung Galaxy Y S5360',7],['Samsung Galaxy Ace S5830',7],['Karbonn K 1212',2],]);      
            var options = {
              title: 'Most Popular Item ',
              hAxis: {title: 'Brand', titleTextStyle: {color: 'red'}}};
            var chart = new google.visualization.ColumnChart(document.getElementById('MPI_chart_div'));
            chart.draw(data, options);
          }
          </script>
    </head>
    <body>
    <h3>COLUMN CHART FOR MOST POPULAR ITEM </h3>
        Select Shop  <select id="MPI_selected_shop" onchange="MPI_set_shop(this.value);">           
                <option value="all_Shops">All Shops</option>
                <option value="1">1</option>
                <option value="2">2</option>
                <option value="3">3</option>
                <option value="4">4</option>
                 </select>
<input type="text" id="sd"  />

        <div id="MPI_chart_div" style="width: 800px; height: 400px;"></div> 
    </body>
    </html>

这是我在脚本标记

中的同一页面中的ajax代码
var xmlHttp

                function MPI_set_shop(str)
                { 
                    alert(str);
                    xmlHttp=GetXmlHttpObject();
                    if (xmlHttp==null)
                    {
                      alert ("Your browser does not support AJAX!");
                      return;
                    } 
                    var url="chart.php";
                    url=url+"?q="+str;
                    alert(url);

                    xmlHttp.onreadystatechange=stateChanged;
                    xmlHttp.open("GET",url,true);
                    xmlHttp.send(null);
                }

                function stateChanged() 
                { 
                    if (xmlHttp.readyState==4)
                    { 
                        document.getElementById("sd").value=xmlHttp.responseText;

                        $st=xmlHttp.responseText;

                        alert($st);

                    }
                }

这是我的chart.php,我从中使用ajax

从mysql获取格式化数据
<?php
 $testid=0;
$testid=$_REQUEST["q"];
//echo $testid;

$con = mysql_connect("localhost","root","");
                if (!$con)
                {
                    die('Could not connect: ' . mysql_error());
                }
                // Select Database
                mysql_select_db("mysql", $con) or die('Could not connect: ' . mysql_error());;

                                    $qMostPopularItem = "SELECT t.pr_id,p.pdt_company_name,p.pdt_model_name,SUM(t.count) AS count FROM tmp AS t INNER JOIN product_mapping AS p ON t.pr_id = p.pr_id AND t.shop_id =$testid GROUP BY pr_id ORDER BY t.count DESC;";

                                        $mpi = mysql_query($qMostPopularItem,$con) or die('Could not fetch MPI: ' . mysql_error());

                                      while($infoMPISW = mysql_fetch_assoc($mpi)) 
                                        { 
                                                echo "['".$infoMPISW['pdt_company_name']." ";
                                                echo $infoMPISW['pdt_model_name'] ."',";
                                                echo $infoMPISW['count'],"],";

                                        }

                      ?>

2 个答案:

答案 0 :(得分:1)

On Ajax Response使用新值再次调用drawChart()函数。以下是我尝试过的代码。

索引文件

<script type="text/javascript" src="https://www.google.com/jsapi"></script>
        <script type="text/javascript"> 
          google.load("visualization", "1", {packages:["corechart"]});
          google.setOnLoadCallback(drawChart);
          function drawChart()
          {
            alert('called');
            var data = google.visualization.arrayToDataTable([['Company & Model', 'Views'],['Samsung Hero Music E1232B',5],['Samsung Galaxy Y S5360',7],['Samsung Galaxy Ace S5830',7],['Karbonn K 1212',2],]);      
            var options = {
              title: 'Most Popular Item ',
              hAxis: {title: 'Brand', titleTextStyle: {color: 'red'}}};
            var chart = new google.visualization.ColumnChart(document.getElementById('MPI_chart_div'));
            chart.draw(data, options);
          }
          function drawChart2()
          {
            alert('called2');
            var data = google.visualization.arrayToDataTable([['Company & Model', 'Views'],['Samsung Music E1232B',5],['Samsung S5360',7],['Samsung S5830',7],['Karbonn K 1212',2],]);      
            var options = {
              title: 'Most Popular Item ',
              hAxis: {title: 'Brand', titleTextStyle: {color: 'red'}}};
            var chart = new google.visualization.ColumnChart(document.getElementById('MPI_chart_div'));
            chart.draw(data, options);
          }
          </script>
<script>
var xmlHttp

                function MPI_set_shop(str)
                { 
                    alert(str);
                    if (window.XMLHttpRequest)
  {// code for IE7+, Firefox, Chrome, Opera, Safari
  xmlhttp=new XMLHttpRequest();
  }
else
  {// code for IE6, IE5
  xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
  }
xmlhttp.onreadystatechange=function()
  {
  if (xmlhttp.readyState==4 && xmlhttp.status==200)
    {
        alert(xmlhttp.responseText);
        //google.load("visualization", str, {packages:["corechart"]});
        //google.setOnLoadCallback(drawChart);
        drawChart2(); // Note down here..
    }
  }
xmlhttp.open("GET","chart.php?q="+str,true);
xmlhttp.send();
                }                
</script>

<h3>COLUMN CHART FOR MOST POPULAR ITEM </h3>
        Select Shop  <select id="MPI_selected_shop" onchange="MPI_set_shop(this.value);">           
                <option value="all_Shops">All Shops</option>
                <option value="1">1</option>
                <option value="2">2</option>
                <option value="3">3</option>
                <option value="4">4</option>
                 </select>
<input type="text" id="sd"  />

        <div id="MPI_chart_div" style="width: 800px; height: 400px;"></div> 

请注意,我已经创建了另一个名为drawChart2()的函数,但如果你调用drawChart(),那么它也会为你提供“被调用”的警告。您只需要传递新值即可。希望以上答案对您有所帮助。最重要的是,除了回调函数之外我什么都没做。 [虽然我更改了javascript ajax代码但不会出现任何问题。]

答案 1 :(得分:0)

您是否查看了谷歌图表的仪表板,您可以在其中绑定图表(例如条形图)和控件(字符串过滤器 - 文本框,类别选择器 - 下拉列表,数字范围选择器 - 滑块)?这是因为我没有看到ChartWrapper和Data Table View选项的实例。

不使用仪表板,一种简单的方法是只是ajax请求新数据并调用chart_ name.draw(new_chart_data,options);这将重绘整个图表。此外,您可能会遇到分辨率/显示问题,具体取决于数据集的大小。