【问题标题】:Flot chart lines with AJAX, PHP and MySQL使用 AJAX、PHP 和 MySQL 绘制图表线
【发布时间】:2018-03-28 06:08:01
【问题描述】:

我正在使用 Flot 插件获取包含两条线(销售和购买)的图表线,例如 this example,但数据在 mysql 数据库中并通过 AJAX 接收。所以我有这个:

HTML:

<div id="graph" class="demo-placeholder"></div>

PHP:

sales.php

<?php 
  $sql = "SELECT * from sales where YEAR(date)='2013'";
  $res = mysql_query($sql);
  $return = [];

while($row = mysql_fetch_array($res)){
    $return[] = [$row['date'],$row['amount']];
}
echo json_encode(array("label"=>"Sales","data"=>$return));
?>

purchases.php

<?php 
  $sql = "SELECT * from purchases where YEAR(date)='2013'";
  $res = mysql_query($sql);
  $return = [];

while($row = mysql_fetch_array($res)){
    $return[] = [$row['date'],$row['amount']];
}
echo json_encode(array("label"=>"Purchases","data"=>$return));
?>

所以,在我的 JS 代码中,我通过 AJAX 获取这些数据并将其放入 Flot 图表线启用工具提示:

var purchases,sales;

    $.ajax({url: "purchases.php",
        type: "GET",
        dataType: "json",
        success: function(resp)
        {
            purchases = resp.data; //Showing result:[["2013-02-01","52"],["2013-03-01","40"],["2013-03-28","200"]]          
        }
    });

    $.ajax({
        url: "sales.php",
        type: "GET",
        dataType: "json",
        success: function(resp)
        {
            sales = resp.data; //Showing result: [["2013-02-05","502"],["2013-03-16","240"],["2013-03-21","260"]]       
        }
    });

var dataset = [
        {
            label: "Purchases",
            data: purchases,
        },
        {
            label: "Sales",
            data: sales,
        }
    ];

var chart_plot_01_settings = {
      series: {
        lines: {
          show: true,
          fill: true
        },
        splines: {
          show: false,
          tension: 0.4,
          lineWidth: 1,
          fill: 0.4
        },
        points: {
          radius: 3,
          show: true 
        },
        shadowSize: 2 
      },
      grid: { 
        verticalLines: true,
        hoverable: true,
        clickable: true,
        tickColor: "#d5d5d5",
        borderWidth: 1,
        color: '#717171'
      },
      colors: ["rgba(38, 185, 154, 0.38)", "rgba(3, 88, 106, 0.38)"],
      xaxis: {
        tickColor: "rgba(51, 51, 51, 0.06)",
        mode: "time",
        tickSize: [1, "month"],
        axisLabel: "Date",
        axisLabelUseCanvas: true,
        axisLabelFontSizePixels: 12,
        axisLabelFontFamily: 'Verdana, Arial',
        axisLabelPadding: 10
      },
      yaxis: {
        ticks: 8,
        axisLabel: "Amount",
        tickColor: "rgba(51, 51, 51, 0.06)",
      },
      tooltip: true, 
    }

if ($("#graph").length){
        $.plot( $("#graph"), dataset,  chart_plot_01_settings );

        $("<div id='tooltip'></div>").css({
            position: "absolute",
            display: "none",
            border: "1px solid #fdd",
            padding: "2px",
            "background-color": "#fee",
            opacity: 0.80
        }).appendTo("body");

        $("#graph").bind("plothover", function (event, pos, item) {

            if (item) {
                var x = item.datapoint[0],
                    y = item.datapoint[1];

                var date = new Date(x);                 

                $("#tooltip").html("Date: " +x + " Amount: "+y).css({top: item.pageY+5, left: item.pageX+5}).fadeIn(200);

            } else {
                $("#tooltip").hide();
            }

        });
    }

问题是图表线不显示任何数据,它是空白的。我在if ($("#graph").length){ 行之后添加了一行console.log(sales),它在控制台中显示undefined,但是如果我将结果放在控制台中成功的AJAX 函数中,它会显示数据。

我该如何解决?我需要一些帮助。

更新

我修改了PHP代码行:

$return[] = [strtotime($row['date'])*1000,$row['amount']];

我修改了JS代码添加了一个show_chart函数:

function show_chart(labell,dataa) { 
    var dataset = [{label: labell,data: dataa}];

    var chart_plot_01_settings = {
      series: {
        lines: {
          show: true,
          fill: true
        },
        splines: {
          show: false,
          tension: 0.4,
          lineWidth: 1,
          fill: 0.4
        },
        points: {
          radius: 3,
          show: true 
        },
        shadowSize: 2 
      },
      grid: { 
        verticalLines: true,
        hoverable: true,
        clickable: true,
        tickColor: "#d5d5d5",
        borderWidth: 1,
        color: '#717171'
      },
      colors: ["rgba(38, 185, 154, 0.38)", "rgba(3, 88, 106, 0.38)"],
      xaxis: {
        tickColor: "rgba(51, 51, 51, 0.06)",
        mode: "time",
        tickSize: [1, "month"],
        //tickLength: 10,
        axisLabel: "Date",
        axisLabelUseCanvas: true,
        axisLabelFontSizePixels: 12,
        axisLabelFontFamily: 'Verdana, Arial',
        axisLabelPadding: 10
      },
      yaxis: {
        ticks: 8,
        axisLabel: "Amount",
        tickColor: "rgba(51, 51, 51, 0.06)",
      },
      tooltip: true,
    }

    $(document).ready(function () {
        $.plot($("#graph"), dataset, chart_plot_01_settings);

        //Tooltip
        $("<div id='tooltip'></div>").css({
            position: "absolute",
            display: "none",
            border: "1px solid #fdd",
            padding: "2px",
            "background-color": "#fee",
            opacity: 0.80
        }).appendTo("body");

        $("#graph").bind("plothover", function (event, pos, item) {

            if (item) {
                var x = item.datapoint[0],
                    y = item.datapoint[1];

                var date = new Date(x);

                $("#tooltip").html("Date: " + ('0' + (date.getMonth()+1)).slice(-2) + '/'+ date.getFullYear()+ " | Amount: "+y).css({top: item.pageY+5, left: item.pageX+5}).fadeIn(200);

            } else {
                $("#tooltip").hide();
            }

        });
    });

} //show chart

var purchases,sales;

    $.ajax({url: "purchases.php",
        type: "GET",
        dataType: "json",
        success: function(resp)
        {
            purchases = resp.data;
            var label1 = resp.label;
            show_chart(label1,purchases);       
        }
    });

    $.ajax({
        url: "sales.php",
        type: "GET",
        dataType: "json",
        success: function(resp)
        {
            sales = resp.data;
            var label2 = resp.label;
            show_chart(label2,sales);
        }
    });

但问题是它只显示 SalesPurchases 图表线,我想显示 both 图表线(Sales 和 Purchases ) 喜欢this example

我该如何解决?

【问题讨论】:

  • 您是否尝试过在 ajax 本身的成功块内实例化浮动图表? imo 是最直接的方法之一(因为无论如何您都需要首先完成服务器响应)。在顶部定义选项,进行ajax调用,然后在成功后实例化flot。 (我会做什么)。顺便检查控制台是否有错误
  • 您是否在 sale.php 和 purchase.php 中打印了 $return 数组?
  • @ArshadShaikh 是的,我得到了信息,但它没有显示在图表中。
  • @Ghost 是的,我也试过了,我把 flot 图表放在了成功和变量数据集中,但显示错误会变得更糟
  • 尝试使用数据集中的虚拟数据并检查实际数据和来自 ajax resposne 的数据。

标签: javascript php mysql ajax flot


【解决方案1】:

您的时间数据格式错误,Flot 需要 JavaScript 时间戳。而不是

[["2013-02-01","52"],["2013-03-01","40"],["2013-03-28","200"]]          

你需要

[[1359676800000,"52"],[1362096000000,"40"],[1364428800000,"200"]]          

使用

strtotime("2013-02-01 UTC") * 1000

在您的 PHP 代码中生成时间戳(请参阅 here)。

【讨论】:

  • 感谢您的回答!我更新了我的问题,添加了更正和 JS 函数,但它只显示了一条图表线
【解决方案2】:

最后我可以解决它,将我的 2 个 php 文件合二为一并放入一个最终数组:

echo json_encode(array($return,$returnn));

在 AJAX 中成功:

success: function(resp)
{
    var result1 = resp[0];//purchases
    var result2 = resp[1];//sales
    show_chart(result1,result2);
}

而在show_cart函数中:

function show_chart(data1,data2) {
    var dataset = [{label: "Purchases",data: data1},{label: "Sales",data: data2}];
    //and continues...
}

【讨论】:

    猜你喜欢
    • 2023-03-20
    • 2010-12-21
    • 2018-08-19
    • 2013-01-05
    • 1970-01-01
    • 2011-01-27
    • 2015-10-14
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多