0

I'm using jqPlot to plot some points in my webApp, so I'm trying this:

var plot10 = $.jqplot ('heightChartDiv', [[3,7,9,1,5,3,8,2,5]]);

and it works fine, I this exact chart here

but when I take it out, to give it a value, like so:

$(document).ready(function(){
var serie1 = [[3,7,9,1,5,3,8,2,5]];
}

function doGraph(){
 var plot10 = $.jqplot ('heightChartDiv', serie1);
}

It doesn't work. am I declaring the variable wrong? please HELP!

~Myy

Myy
  • 18,107
  • 11
  • 37
  • 57

1 Answers1

1

Your variable scoping is all off. The variable serie1 has local scope to the anonymous function defined in $(document).ready event. Read up on javascript scope here and here.

Perhaps something like this:

// the document ready will fire when the page is finished rendering
// inline javascript as you've done with your doGraph will fire as the page renders
$(document).ready(function(){

  // first define graph function
  // make the series an argument to the function
  doGraph = function(someSeries){
    var plot10 = $.jqplot ('heightChartDiv', someSeries);
  }

  // now call the function with the variable
  var serie1 = [[3,7,9,1,5,3,8,2,5]];
  doGraph(serie1);

}

EDITS IN RESPONSE TO COMMENT

See this below example:

$(document).ready(function(){

  var a = 1;

  someFunc = function(){
    var b = 2;
    alert(a);                   
  }

  someFunc();  // this works
  alert(b);  // this produces an error

});​

Here the variable a is considered global to the function someFunc. A variable declared in someFunc, though, does not persist outside of it.

Community
  • 1
  • 1
Mark
  • 106,305
  • 20
  • 172
  • 230
  • Well it doesn't make any sense then, because I have an ajax call that sets a variable with a value in the $(document).ready(function(){ and when I call the doGraph() it gets the correct values. I just don't get why it would be any different. ( not saying you are wrong, just that it's not very intuitive) – Myy Jul 11 '12 at 03:36