• 0

[Javascript +php] Array of Arrays from JSON not quite working, what am I doing wrong?


Question

I've working on a front end dashboard for a set of tools I wrote for our support department, and ended up purchasing a template design to make things look pretty.   In the template, there are graphs, and i've been modifying the javascript code to suit my needs, however JS is not one of my strong points, and I'm stuck trying to tweak something

 

In the template, they use the following 

var data = new Array ();
data.push ([[5,66],[6,65],[7,68],[8,67],[9,64],[10,68],[11,73],[12,66],[13,70],[14,72],[15,74],[16,75],[17,67],[18,67],[19,39],[20,25]]);

to create a array of values to feed to a bar chart.    I need to create this from results from a mysql database, so I tried to change this into a for loop, but it doesn't seem to work.  The only way I seem to be able to create the array in a for loop, is the following:

var data = new Array ();
    var ds = new Array();	
	var namespacedata = [];
	for (var j=5; j<20; j++) {
		namespacedata.push([j,66]);
	}
	data.push(namespacedata);

this works, giving me a bunch of bars with "66" for the value.  So I wrote a php script that json encodes results from a mysql DB, with the results looking like this:

[{"NAMESPACE":"5","used":"65"},{"NAMESPACE":"6","used":"63"},{"NAMESPACE":"7","used":"67"},{"NAMESPACE":"8","used":"66"},{"NAMESPACE":"9","used":"63"},{"NAMESPACE":"10","used":"66"},{"NAMESPACE":"11","used":"71"},{"NAMESPACE":"12","used":"65"},{"NAMESPACE":"13","used":"70"},{"NAMESPACE":"14","used":"70"},{"NAMESPACE":"15","used":"73"},{"NAMESPACE":"16","used":"73"},{"NAMESPACE":"17","used":"65"},{"NAMESPACE":"18","used":"67"},{"NAMESPACE":"19","used":"41"},{"NAMESPACE":"20","used":"25"}]

however when I try the following, it doesn't seem to work:

  var data = new Array ();
    var ds = new Array();
    var namespacedata = [];
$.getJSON("resources/get_namespace_usage.php", function(result) {
       }
.done(function() {
   $.each(result, function(i, item) {

       namespacedata.push([Number(item.NAMESPACE),Number(item.used)]);
   });

data.push(namespacedata);

Whats strange, is that if I put a "namespacedata.push([21,66]);" right before the "data.push" line, my graph suddenly shows a single bar, with a value of 66 (or whatever i put as it's value).

 

If i throw in some debugging "alerts" or Console.logs, the results I get look the same between the working code, and what I'm trying to do as a for loop, (array of arrays, etc)  so I can't figure out what my problem is.

 

Anyone know what I'm doing wrong?

Link to comment
Share on other sites

1 answer to this question

Recommended Posts

  • 0

solved, the plot happens before the data variable gets filled, so i moved the plot to inside getJSON's success handler, and now it works.

Link to comment
Share on other sites

This topic is now closed to further replies.