SitePoint Sponsor

User Tag List

Page 1 of 2 12 LastLast
Results 1 to 25 of 27
  1. #1
    SitePoint Wizard
    Join Date
    May 2012
    Posts
    1,159
    Mentioned
    1 Post(s)
    Tagged
    0 Thread(s)

    Post 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

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

    HTML Code:
    <!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.

  2. #2
    SitePoint Wizard bronze trophy chris.upjohn's Avatar
    Join Date
    Apr 2010
    Location
    Melbourne, AU
    Posts
    2,198
    Mentioned
    17 Post(s)
    Tagged
    1 Thread(s)
    How are you returning your data arrays from your AJAX request? By that I mean are you returning single arrays e.g.

    Code javascript:
    [
        [65,59,90,81,56,55,40],
        [65,59,90,81,56,55,40]
    ]

    or are you returning entire objects?

    Code javascript:
    [{
        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]
    }]

  3. #3
    SitePoint Wizard
    Join Date
    May 2012
    Posts
    1,159
    Mentioned
    1 Post(s)
    Tagged
    0 Thread(s)
    Hi , I echo the json and this is the output.

    Code:
     {"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.

  4. #4
    SitePoint Wizard bronze trophy chris.upjohn's Avatar
    Join Date
    Apr 2010
    Location
    Melbourne, AU
    Posts
    2,198
    Mentioned
    17 Post(s)
    Tagged
    1 Thread(s)
    I haven't tested this but it should be a good direction as to how you can achieve this.

    Code JavaScript:
    $(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.

  5. #5
    SitePoint Wizard
    Join Date
    May 2012
    Posts
    1,159
    Mentioned
    1 Post(s)
    Tagged
    0 Thread(s)
    Quote Originally Posted by chris.upjohn View Post
    I haven't tested this but it should be a good direction as to how you can achieve this.

    Code JavaScript:
    $(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]);"

  6. #6
    SitePoint Wizard bronze trophy chris.upjohn's Avatar
    Join Date
    Apr 2010
    Location
    Melbourne, AU
    Posts
    2,198
    Mentioned
    17 Post(s)
    Tagged
    1 Thread(s)
    Replace that line with the following.

    Code javascript:
    theChartData.data.push(chartData[j]);

  7. #7
    SitePoint Wizard
    Join Date
    May 2012
    Posts
    1,159
    Mentioned
    1 Post(s)
    Tagged
    0 Thread(s)
    Quote Originally Posted by chris.upjohn View Post
    Replace that line with the following.

    Code javascript:
    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++){

  8. #8
    SitePoint Wizard bronze trophy chris.upjohn's Avatar
    Join Date
    Apr 2010
    Location
    Melbourne, AU
    Posts
    2,198
    Mentioned
    17 Post(s)
    Tagged
    1 Thread(s)
    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?

  9. #9
    SitePoint Wizard
    Join Date
    May 2012
    Posts
    1,159
    Mentioned
    1 Post(s)
    Tagged
    0 Thread(s)
    Quote Originally Posted by chris.upjohn View Post
    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...

  10. #10
    Gre aus'm Pott gold trophysilver trophybronze trophy
    Pullo's Avatar
    Join Date
    Jun 2007
    Location
    Germany
    Posts
    6,075
    Mentioned
    219 Post(s)
    Tagged
    12 Thread(s)
    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.

  11. #11
    SitePoint Wizard
    Join Date
    May 2012
    Posts
    1,159
    Mentioned
    1 Post(s)
    Tagged
    0 Thread(s)
    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.

  12. #12
    Gre aus'm Pott gold trophysilver trophybronze trophy
    Pullo's Avatar
    Join Date
    Jun 2007
    Location
    Germany
    Posts
    6,075
    Mentioned
    219 Post(s)
    Tagged
    12 Thread(s)
    Hi jemz,

    I have to go to work right now 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:

    Code:
    {
    "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?

  13. #13
    SitePoint Wizard
    Join Date
    May 2012
    Posts
    1,159
    Mentioned
    1 Post(s)
    Tagged
    0 Thread(s)
    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.

  14. #14
    SitePoint Wizard bronze trophy chris.upjohn's Avatar
    Join Date
    Apr 2010
    Location
    Melbourne, AU
    Posts
    2,198
    Mentioned
    17 Post(s)
    Tagged
    1 Thread(s)
    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.

    Code javascript:
    $(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
                });
            }
        });
     
    });

  15. #15
    Gre aus'm Pott gold trophysilver trophybronze trophy
    Pullo's Avatar
    Join Date
    Jun 2007
    Location
    Germany
    Posts
    6,075
    Mentioned
    219 Post(s)
    Tagged
    12 Thread(s)
    Ok, well you can do it like this:

    Code:
    <!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:

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

  16. #16
    Community Advisor bronze trophy
    fretburner's Avatar
    Join Date
    Apr 2013
    Location
    Brazil
    Posts
    1,446
    Mentioned
    45 Post(s)
    Tagged
    13 Thread(s)
    Quote Originally Posted by Pullo View Post
    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:

    Code:
    {
      "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.

  17. #17
    SitePoint Wizard
    Join Date
    May 2012
    Posts
    1,159
    Mentioned
    1 Post(s)
    Tagged
    0 Thread(s)
    HI pullo,

    It would be better to return something like this:

    Code:
    {
      "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

  18. #18
    SitePoint Wizard
    Join Date
    May 2012
    Posts
    1,159
    Mentioned
    1 Post(s)
    Tagged
    0 Thread(s)
    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

  19. #19
    SitePoint Wizard
    Join Date
    May 2012
    Posts
    1,159
    Mentioned
    1 Post(s)
    Tagged
    0 Thread(s)
    Hi pullo,

    It would be better to return something like this:

    Code:
    {
      "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.

    Code:
      $(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.

  20. #20
    Gre aus'm Pott gold trophysilver trophybronze trophy
    Pullo's Avatar
    Join Date
    Jun 2007
    Location
    Germany
    Posts
    6,075
    Mentioned
    219 Post(s)
    Tagged
    12 Thread(s)
    Quote Originally Posted by jemz View Post
    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?
    Well, it should be as simple as doing this:

    Code:
    <!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>

  21. #21
    Gre aus'm Pott gold trophysilver trophybronze trophy
    Pullo's Avatar
    Join Date
    Jun 2007
    Location
    Germany
    Posts
    6,075
    Mentioned
    219 Post(s)
    Tagged
    12 Thread(s)
    Quote Originally Posted by jemz View Post
    Why my graph did not move,This is how i do it.
    Can you change your success callback to this:

    Code:
    success: function(data){
      console.log(data);
    }
    and post the results.

  22. #22
    SitePoint Wizard
    Join Date
    May 2012
    Posts
    1,159
    Mentioned
    1 Post(s)
    Tagged
    0 Thread(s)
    HI pullo,

    The reason why my graph did not move because
    Code:
    console.log(data.regularData)
    Output to this
    Code:
    ["7.00","116.00","25.00","60.00","26.00"]
    how do i removed those double quotes so that it would look like this
    Code:
    [7.00,116.00,25.00,60.00,26.00]

    Thank you in advance.

  23. #23
    SitePoint Wizard
    Join Date
    May 2012
    Posts
    1,159
    Mentioned
    1 Post(s)
    Tagged
    0 Thread(s)
    Quote Originally Posted by Pullo View Post
    Can you change your success callback to this:

    Code:
    success: function(data){
      console.log(data);
    }
    and post the results.
    Hi pullo, sorry i did not see your post...

    Okay this is the result

    Code:
    casualData	["26.00", "1000.00"]
    	
    labels	["January", "February", "March", 2 more...]
    	
    regularData	["7.00", "116.00", "25.00", 2 more...]
    Thank you in advance.

  24. #24
    Community Advisor bronze trophy
    fretburner's Avatar
    Join Date
    Apr 2013
    Location
    Brazil
    Posts
    1,446
    Mentioned
    45 Post(s)
    Tagged
    13 Thread(s)
    Quote Originally Posted by jemz View Post
    HI pullo,

    The reason why my graph did not move because
    Code:
    console.log(data.regularData)
    Output to this
    Code:
    ["7.00","116.00","25.00","60.00","26.00"]
    how do i removed those double quotes so that it would look like this
    Code:
    [7.00,116.00,25.00,60.00,26.00]

    Thank you in advance.
    Hey jemz,

    You can get rid of the quotes by making a small change to the PHP that outputs the data:
    PHP Code:
    $results['regularDate'][] = (float)$row['amount']; 
    Putting (float) in front of the variable will cause PHP to cast the string to a float value.

  25. #25
    SitePoint Wizard
    Join Date
    May 2012
    Posts
    1,159
    Mentioned
    1 Post(s)
    Tagged
    0 Thread(s)
    Quote Originally Posted by fretburner View Post
    Hey jemz,

    You can get rid of the quotes by making a small change to the PHP that outputs the data:
    PHP Code:
    $results['regularDate'][] = (float)$row['amount']; 
    Putting (float) in front of the variable will cause PHP to cast the string to a float value.
    HI fretburner,Thank you,it's working


Bookmarks

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •