duanjiao5543 2018-03-27 04:30
浏览 101
已采纳

使用AJAX,PHP和MySQL绘制图表行

I'm using Flot plugin to get a chart line with two lines (Sales and Purchases) like this example but data is in mysql database and being received via AJAX. So I have this:

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));
?>

So, in my JS code I get this data via AJAX and put it a Flot chart line enabling tooltip:

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();
            }

        });
    }

The problem is chart line doesn't display any data, It's in blank. I added a line console.log(sales) after if ($("#graph").length){ line and it shows undefined in console but it shows data if I put result in console inside success AJAX function.

enter image description here

How can I fix it? I'd like some help.

UPDATE

I modified PHP code line:

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

I modified JS code adding a show_chart function:

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);
        }
    });

But the problem it's only showing Sales or Purchases chart line and I want to show both chart lines (Sales and Purchases) like this example.

How can I fix it?

  • 写回答

2条回答 默认 最新

  • dpr26232 2018-03-27 22:08
    关注

    Finally I could resolve it joining my 2 php files in one and put a final array:

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

    In AJAX success:

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

    And in show_cart function:

    function show_chart(data1,data2) {
        var dataset = [{label: "Purchases",data: data1},{label: "Sales",data: data2}];
        //and continues...
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 Arcgis相交分析无法绘制一个或多个图形
  • ¥15 seatunnel-web使用SQL组件时候后台报错,无法找到表格
  • ¥15 fpga自动售货机数码管(相关搜索:数字时钟)
  • ¥15 用前端向数据库插入数据,通过debug发现数据能走到后端,但是放行之后就会提示错误
  • ¥30 3天&7天&&15天&销量如何统计同一行
  • ¥30 帮我写一段可以读取LD2450数据并计算距离的Arduino代码
  • ¥15 飞机曲面部件如机翼,壁板等具体的孔位模型
  • ¥15 vs2019中数据导出问题
  • ¥20 云服务Linux系统TCP-MSS值修改?
  • ¥20 关于#单片机#的问题:项目:使用模拟iic与ov2640通讯环境:F407问题:读取的ID号总是0xff,自己调了调发现在读从机数据时,SDA线上并未有信号变化(语言-c语言)