最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Pass variable to datapoints in canvasjs - Stack Overflow

programmeradmin3浏览0评论

I am trying to make line garph from canvasjs using database data. But I am having problem with passing data to datapoints.

 $.ajax({
    dataType : "json",
    type: "POST",
    url: base_url + 'index.php/dashboard/line_graph',
    data: {},
    success: function(data)
    {
        for(var i = 0; i < data.length; i++)
        {
            var firstdate = data[i].nextdate;
            var res = firstdate.replace(/[-]/g,','); 
            fd += '{ x: new Date(' + res + '), y:' + data[i].count +'},';
        }
        var fin = fd.slice(0,-1);
         finals = "[" + fin + "]";            
                var chart = new CanvasJS.Chart("chartContainer",
                  {

                    title:{
                    text: "Booking - per month (DEMO)"
                    },
                     data: [
                    {
                      type: "line",

                      dataPoints: finals

                    }
                    ]
                  });

                  chart.render();

    }
});

When I alert finals and copy paste the alerted data to datapoints and run then its working. But when variable containing same data is passed to datapoint then its not working.

In console log, I get this error.

 TypeError: l.dataPoints[q].x is undefined

The format of the datapoints is this. And variable finals also contains same data when I do alert.

 [
 { x: new Date(2015,03,6), y:4},
 { x: new Date(2015,03,11), y:0},
 { x: new Date(2015,03,16), y:0},
 { x: new Date(2015,03,21), y:0},
 { x: new Date(2015,03,26), y:0},
 { x: new Date(2015,03,31), y:14}
 ]

My page returns this json_encode format.

 [
 {"firstdate":"2015-03-01","nextdate":"2015-03-6","count":"4"},    
 {"firstdate":"2015-03-6","nextdate":"2015-03-11","count":"0"},
 {"firstdate":"2015-03-11","nextdate":"2015-03-16","count":"0"},
 {"firstdate":"2015-03-16","nextdate":"2015-03-21","count":"0"},
 {"firstdate":"2015-03-21","nextdate":"2015-03-26","count":"0"},
 {"firstdate":"2015-03-26","nextdate":"2015-03-31","count":"14"}
 ]

I don't get the issues. Please Help.

I am trying to make line garph from canvasjs using database data. But I am having problem with passing data to datapoints.

 $.ajax({
    dataType : "json",
    type: "POST",
    url: base_url + 'index.php/dashboard/line_graph',
    data: {},
    success: function(data)
    {
        for(var i = 0; i < data.length; i++)
        {
            var firstdate = data[i].nextdate;
            var res = firstdate.replace(/[-]/g,','); 
            fd += '{ x: new Date(' + res + '), y:' + data[i].count +'},';
        }
        var fin = fd.slice(0,-1);
         finals = "[" + fin + "]";            
                var chart = new CanvasJS.Chart("chartContainer",
                  {

                    title:{
                    text: "Booking - per month (DEMO)"
                    },
                     data: [
                    {
                      type: "line",

                      dataPoints: finals

                    }
                    ]
                  });

                  chart.render();

    }
});

When I alert finals and copy paste the alerted data to datapoints and run then its working. But when variable containing same data is passed to datapoint then its not working.

In console log, I get this error.

 TypeError: l.dataPoints[q].x is undefined

The format of the datapoints is this. And variable finals also contains same data when I do alert.

 [
 { x: new Date(2015,03,6), y:4},
 { x: new Date(2015,03,11), y:0},
 { x: new Date(2015,03,16), y:0},
 { x: new Date(2015,03,21), y:0},
 { x: new Date(2015,03,26), y:0},
 { x: new Date(2015,03,31), y:14}
 ]

My page returns this json_encode format.

 [
 {"firstdate":"2015-03-01","nextdate":"2015-03-6","count":"4"},    
 {"firstdate":"2015-03-6","nextdate":"2015-03-11","count":"0"},
 {"firstdate":"2015-03-11","nextdate":"2015-03-16","count":"0"},
 {"firstdate":"2015-03-16","nextdate":"2015-03-21","count":"0"},
 {"firstdate":"2015-03-21","nextdate":"2015-03-26","count":"0"},
 {"firstdate":"2015-03-26","nextdate":"2015-03-31","count":"14"}
 ]

I don't get the issues. Please Help.

Share Improve this question edited Apr 2, 2015 at 8:21 user254153 asked Apr 2, 2015 at 7:58 user254153user254153 1,8835 gold badges44 silver badges87 bronze badges 2
  • Hi, can you add what data your page index.php/dashboard/line_graph returns ? – jmgross Commented Apr 2, 2015 at 8:09
  • Hi i had edited my question. linegraph returns json format. – user254153 Commented Apr 2, 2015 at 8:22
Add a ment  | 

5 Answers 5

Reset to default 4

You don't have to create finals variable like a string, you can use directly object format of Javascript :

$.ajax({
    type: "POST",
    url: base_url + 'index.php/dashboard/line_graph',
    data: {},
    success: function(data)
    {
        var tabData = JSON.parse(data);
        var finals = [];
        for(var i = 0; i < tabData.length; i++)
        {
            var firstdate = tabData[i].nextdate;
            var res = firstdate.split('-'); 
            finals.push({ 'x': new Date(res[2],res[1],res[0]), 'y': tabData[i].count });
        }
        var chart = new CanvasJS.Chart("chartContainer",{
            title:{
                text: "Booking - per month (DEMO)"
            },
            data: [
                {
                    type: "line",
                    dataPoints: finals
                }
            ]
        });

        chart.render();
    }
});

Don't create every thing as a string:

var finals = [];
for(var i = 0; i < data.length; i++)
{
    var firstdate = data[i].nextdate;
    var res = firstdate.replace(/[-]/g,','); 
    finals.push({ x: new Date(res), y: parseInt(data[i].count)});
}

You can build your array data in view, using loop from variable of php, for example:

<script type="text/javascript">
     var current_month = [];
     <?php foreach ($grafico_current as $key => $value) { ?>
        current_month.push({ 'x': new Date(<?php echo $value['ano']; ?>,<?php echo $value['mes']; ?>,<?php echo $value['dia']; ?>), 'y': <?php echo $value['total']; ?> });
     <?php } ?>
 </script>

After it, set the dataPoint with this new var:

dataPoints: current_month

CanvasJS only allows you to pass things like x,y,label, IndexLabel. So if you want to pass the ID (or multiple ids) of drilldown data, you can't. I tried to think of a way around this. The only thing that I have e up with was to create a dummy series. I set the indexLabel to the dummy series to be a JSON string of data. Then when I click, I can get the y axis index from e.dataPointIndex

DATA.push({ showInLegend: false, markerType: 'none',label: 
d[i].cv_quality_metric_period_ending, y:   parseFloat((Math.round(  
d[i].cv_quality_metric_value * 100) / 100).toFixed(2)), indexLabel: '{"metric_id":' + metric_id + '}'  });

The series that has the click function looks like this:

R4Q.push({ label: d[i].cv_quality_metric_period_ending, indexLabel: 
d[i].cv_quality_metric_R4Q, y:  parseFloat((Math.round(  
d[i].cv_quality_metric_r4q * 100) / 100).toFixed(2)) ,click: function(e){ 
chartClickHandler( metric_id, e) },markerColor: markerColor, 
markerType:markerType,markerSize: markerSize});

The metric_id is the same for all data, so it is correct and accessible.

Then I can look up the data for that column in the dummy series by referencing var index = e.dataPointIndex //clicked y column starts at 0 so 2 is the 3rd y column of data.

function chartClickHandler(metric_id,e){
var index = e.dataPointIndex
var data = e.chart.data[2].dataPoints[index].indexLabel
data = JSON.parse(data)
//do what you need to do with the passed data
}

In the JSON that constructs the chart I add the dummy series

{
        name: "data", 
        type: "spline",       
        showInLegend: false,        
        legendMarkerType: 'none',        
    visible:false,
        dataPoints: DATA
        }

Pass data like dataPoints: JSON.parse(data)

instead of dataPoints: data

发布评论

评论列表(0)

  1. 暂无评论