How do i load data on this

Hi, Anyone knows how to use this chartjs ?..I am confuse on this on how am i going to load datasets via jquery.ajax

I want to replace this part

data : [65,59,90,81,56,55,40]

And this

data : [28,48,40,19,96,27,100]

to the data that i requested via ajax.but i am confuse on how to do this or to achieve this.

if i have this ajax returned with json encoded


   $(function(){
    $.ajax({
      type: 'post',
      url: 'requestingdata.php',
      success: function(data){
           //How do i load now this returned data to the datasets "data:" ?
    }
  });
});


<!doctype html>
<html>
	<head>
		<title>Bar Chart</title>
		<script src="Chart.js"></script>
		<meta name = "viewport" content = "initial-scale = 1, user-scalable = no">
		<style>
			canvas{
			}
		</style>
	</head>
	<body>
		<canvas id="canvas" height="450" width="600"></canvas>


	<script>

		var barChartData = {
			labels : ["January","February","March","April","May","June","July"],
			datasets : [
				{
					fillColor : "rgba(220,220,220,0.5)",
					strokeColor : "rgba(220,220,220,1)",
					data : [65,59,90,81,56,55,40]
				},
				{
					fillColor : "rgba(151,187,205,0.5)",
					strokeColor : "rgba(151,187,205,1)",
					data : [28,48,40,19,96,27,100]
				}
			]
			
		}

	var myLine = new Chart(document.getElementById("canvas").getContext("2d")).Bar(barChartData);
	
	</script>
	</body>
</html>

please help me on this

Thank you in advance.:slight_smile:

How are you returning your data arrays from your AJAX request? By that I mean are you returning single arrays e.g.

[
    [65,59,90,81,56,55,40],
    [65,59,90,81,56,55,40]
]

or are you returning entire objects?

[{
    fillColor : "rgba(151,187,205,0.5)",
    strokeColor : "rgba(151,187,205,1)",
    data : [28,48,40,19,96,27,100]
}, {
    fillColor : "rgba(151,187,205,0.5)",
    strokeColor : "rgba(151,187,205,1)",
    data : [28,48,40,19,96,27,100]
}]

Hi , I echo the json and this is the output.


 {"Regular":{"January":"20","February":"50","March":"12","April":"45","May":"30","June":"11","July":"13"},
"Basic":{"January":"48","February":"56","March":"21","April":"86","May":"93","June":"100","July":"30"}}

Hope this helps. :slight_smile:

I haven’t tested this but it should be a good direction as to how you can achieve this.

$(function() {	var addMonthToLabels = function(month) {
		var wasFound = true;


		for (var i in labels) {
			wasFound = labels[i] === month;
		}


		if (!wasFound) {
			labels.push(month);
		}
	},
	count  = 0,
	labels = datasets = [];


	$.ajax({
		type    : 'post',
		url     : 'requestingdata.php',
		success : function(data) {
			for (var i in data) {
				if (data.hasOwnProperty(i)) {
					var chartData    = data[i],
						theChartData = {
							fillColor   : 'rgba(0,0,0, 0.' + (100 - (count * 5)) + ')',
							strokeColor : 'rgba(57,57,57, 1)',
							data        : []
						};


					for (var j in chartData) {
						if (chartData.hasOwnProperty(j)) {
							addMonthToLabels(j);
							theChartData.push(chartData[j]);
						}
					}


					datasets.push(theChartData);
					count++;
				}
			}


			var myLine = new Chart(document.getElementById('canvas').getContext('2d')).Bar({
				labels   : labels,
				datasets : datasets
			});
		}
	});
});

One thing you may want to do is make your data less complex by abstracting the labels into their own array and the data into their own array that way 20% of the above code can be eliminated altogether.

hi, it says theChartData is not a function in this line " theChartData.push(chartData[j]);"

Replace that line with the following.

theChartData.data.push(chartData[j]);

Hi chris, another error after i fixed the line
this is the new error

TypeError: data.datasets[i].data is undefined
[Break On This Error]

for (var j=0; j<data.datasets[i].data.length; j++){

That looks to be an error occurring within the bar graph library itself, do you have a working copy of the page that I can look at?

Hi chris, I don’t have live server to put this up…i am in my local machine…

Hey jemz,

I kind of stumbled across this thread.
I don’t have any experience of using chart.js, but would like to try it out and this seems like a good opportunity.
So, would you mind explaining in high level terms, what exactly it is that you are trying to achieve (just assume I know nothing :))

If, as Chris suggests, Chart.js is exhibiting a bug, then maybe we can find a different solution.
Also, we should report the bug to the developers.

Hi pullo,

what exactly it is that you are trying to achieve

Okay, What i want is to query or to fetch records to my employee table and sets the data to the graph…getting all the the status having “Regular” and “Casual” in every month.
the result of this query will be encoded to json.

so this is what the data it looks like after the request to the server

{"Regular":{"January":"20","February":"50","March":"12","April":"45","May":"30","June":"11","July":"13"},

“Casual”:{“January”:“48”,“February”:“56”,“March”:“21”,“April”:“86”,“May”:“93”,“June”:“100”,“July”:“30”}}

Now, how do i sets the data to the graph returned by jquery.ajax. ?

Thank you in advance.

Hi jemz,

I have to go to work right now :frowning: but will write you a proper answer when I get back.

In the mean time, just to be clear, your ajax call returns this data:

{
"Regular":{"January":"20","February":"50","March":"12","April":"45","May":"30","June":"11","July":"13"},
"Casual":{"January":"48","February":"56","March":"21","April":"86","May":"93","June":"100","July":"30"}
}

You then want to display this data using chart.js.
This much I have understood.

So my next question:
Which kind of chart do you wish to use to display this data?
Judging by your code in your first post, it seems that you want to make a bar chart. Is this correct?

Hi pullo, Yes,that is the data return by ajax,… I want to use the chart.js and the kind of chart to use is Bar Chart :),

Thank you in advance.

Try the following, I finally had a chance to test the code out on the library myself and found some bugs in my code which have now been revolved.

$(function() {

    var addMonthToLabels = function(month) {
        var wasFound = false;

        for (var i in labels) {
            wasFound = labels[i] === month;

            if (wasFound) {
                return;
            }
        }

        labels.push(month);
    },
    count    = 0,
    datasets = [],
    labels   = [];

    $.ajax({
        type    : 'post',
        url     : 'requestingdata.php',
        success : function(data) {
            for (var i in data) {
                if (data.hasOwnProperty(i)) {
                    var chartData    = data[i],
                        theChartData = {
                            fillColor   : 'rgba(0,0,0, 0.' + (100 - (count * 10)) + ')',
                            strokeColor : 'rgba(57,57,57, 1)',
                            data        : []
                        };

                    for (var j in chartData) {
                        if (chartData.hasOwnProperty(j)) {
                            addMonthToLabels(j);
                            theChartData.data.push(chartData[j]);
                        }
                    }

                    datasets.push(theChartData);
                    count++;
                }
            }

            var myLine = new Chart(document.getElementById('canvas').getContext('2d')).Bar({
                labels   : labels,
                datasets : datasets
            });
        }
    });

});

Ok, well you can do it like this:

<!doctype html>
<html>
  <head>
    <title>Bar Chart</title>
    <script src="../Chart.js"></script>
  </head>
  <body>
    <canvas id="canvas" height="450" width="600"></canvas>
    
    <script>
      var ajaxData = {
        "Regular":{"January":"20","February":"50","March":"12","April":"45","May":"30","June":"11","July":"13"},
        "Casual":{"January":"48","February":"56","March":"21","April":"86","May":"93","June":"100","July":"30"}
      }
      
      var regular = ajaxData["Regular"],
          casual = ajaxData["Casual"],
          labels = [],
          regularData = [],
          casualData = [];
      
      // get labels
      for (var key in regular) {
        if (regular.hasOwnProperty(key)) {
          labels.push(key);
        }
      }
      
      // get data
      for (var key in regular) {
        if (regular.hasOwnProperty(key)) {
          regularData.push(Number(regular[key]));
        }
      }
  
      for (var key in casual) {
        if (casual.hasOwnProperty(key)) {
          casualData.push(Number(casual[key]));
        }
      }
      
      var barChartData = {
        labels : labels,
        datasets : [
          {
            fillColor : "rgba(220,220,220,0.5)",
            strokeColor : "rgba(220,220,220,1)",
            data : regularData
          },
          {
            fillColor : "rgba(151,187,205,0.5)",
            strokeColor : "rgba(151,187,205,1)",
            data : casualData
          }
        ]
      }
  
      var myLine = new Chart(document.getElementById("canvas").getContext("2d")).Bar(barChartData);
    </script>
  </body>
</html>

However, as Chris already said, your data structures are not perfect.
For instance I am deriving the labels from the keys of one of the objects that is being returned, which is a bit hacky.

It would be better to return something like this:

{
  "labels" : ["January", "February", "March", "April", "May", "June", "July"],
  "regularData" : [20, 50, 12, 45, 30, 11, 13],
  "casualData" : [48, 56, 21, 86, 93, 100, 30] 
}

There was a previous thread where jemz asked about the PHP side of this app, and I gave him some advice on his DB query and about returning the results as JSON.

Jemz, having seen what you’re trying to achieve with the data here in this thread, can you post the PHP code which outputs the data? I think it needs to be revisited to help simplify what you’re trying to do here.

HI pullo,

It would be better to return something like this:

{
  "labels" : ["January", "February", "March", "April", "May", "June", "July"],
  "regularData" : [20, 50, 12, 45, 30, 11, 13],
  "casualData" : [48, 56, 21, 86, 93, 100, 30]
}

Okay I change now the SQL statement (credits to fretburner)and the echoed encoded json is similar now in the above example.

so is there any changes to your code now the solution that you provided?

Thank you in advance :slight_smile:

Hi chris.upjohn

I made a changes for my sql statement so that the echoed encoded json will be output like this.

{
“labels” : [“January”, “February”, “March”, “April”, “May”, “June”, “July”],
“regularData” : [20, 50, 12, 45, 30, 11, 13],
“casualData” : [48, 56, 21, 86, 93, 100, 30]
}

Thank you in advance :slight_smile:

Hi pullo,

It would be better to return something like this:

{
  "labels" : ["January", "February", "March", "April", "May", "June", "July"],
  "regularData" : [20, 50, 12, 45, 30, 11, 13],
  "casualData" : [48, 56, 21, 86, 93, 100, 30] 
}

why my graph did not move,This is how i do it.


  $(function(){


            $.ajax({
                type: 'post',
                url: 'requestingdata.php',
                success: function(data){
                  var lbl = data.labels;
                  var regular = data.regularData;
                  var casual = data.casualData;

                
                   var datas = {
                        labels: lbl,
                        datasets: [
                            {
                                fillColor: "rgba(220,220,220,0.5)",
                                strokeColor: "rgba(220,220,220,1)",
                                data : regular
                            },

                            {
                                fillColor : "rgba(151,187,205,0.5)",
                                strokeColor : "rgba(151,187,205,1)",
                                data : casual
                            }

                        ]
                    };

                    var ctx = document.getElementById("canvas").getContext("2d");

                    new Chart(ctx).Bar(datas);

                }
            });


        });


Thank you in advance.

Well, it should be as simple as doing this:

<!doctype html>
<html>
  <head>
    <title>Bar Chart</title>
    <script src="../Chart.js"></script>
  </head>
  <body>
    <canvas id="canvas" height="450" width="600"></canvas>
    
    <script>
      var ajaxData = {
        "labels" : ["January", "February", "March", "April", "May", "June", "July"],
        "regularData" : [20, 50, 12, 45, 30, 11, 13],
        "casualData" : [48, 56, 21, 86, 93, 100, 30] 
      }
      
      var barChartData = {
        labels : ajaxData["labels"],
        datasets : [
          {
            fillColor : "rgba(220,220,220,0.5)",
            strokeColor : "rgba(220,220,220,1)",
            data : ajaxData["regularData"]
          },
          {
            fillColor : "rgba(151,187,205,0.5)",
            strokeColor : "rgba(151,187,205,1)",
            data : ajaxData["casualData"]
          }
        ]
      }
  
      var myLine = new Chart(document.getElementById("canvas").getContext("2d")).Bar(barChartData);
    </script>
  </body>
</html>