0

I'm trying to declare a global array so I can use the array in another function:

columnArray = new Array();

But for some reason it's not global I see the array in the function I created it in, but not outside that function. Here's my full code:

//Get column header variables
    jQuery.ajax({
        url: 'myJsonFile.json',
        async: true,
        dataType: 'json',
        error: function(result) {
        console.log("There was an error loading the json.");
    },
        success: function(data) {

        columnArray = new Array ();
        var i;
            for(i = 0; i < data.columnVars.length; i++)
            {
                columnArray[i] = data.columnVars[i].vars;
            }
        }
    });
Jeff Mcbride
  • 453
  • 2
  • 6
  • 19
  • what kind of error have you got ? maybe your data.columnVars is empty, no ? – Anonymous0day Nov 03 '15 at 16:41
  • Are you accessing the array after the execution of success()? – Ganesh Kumar Nov 03 '15 at 16:41
  • ajax is async, that's why you should never use any global variable regarding handling ajax result – A. Wolff Nov 03 '15 at 16:42
  • To expand on what @GaneshKumar said, the `success` function may not be called until much later than the rest of the code (if at all). – Ypnypn Nov 03 '15 at 16:44
  • In the console the array says undefined. I know ajax is async (you can change that if need be though). And, yes, I am accessing the array after the execution of success(). Thinking about about it, I really don't HAVE to use the array in a separate function, I could combine the functions but I still would like to know if there is an answer to the question. – Jeff Mcbride Nov 03 '15 at 16:48
  • If you really want a global, declare it as global before your ajax call with : `var columnArray;` and in your success function fill it like you want and to check it, put `console.log(columnArray)` before the end of your success function after your loop. Try that and tell us. – Anonymous0day Nov 03 '15 at 18:01

0 Answers0