0

I have

jQuery(document).ready(function() 
{

    jQuery.get('data/php/traces_pos.csv', function(data) { var routes = jQuery.csv()(data); });

//if I use here 

for (i=0;i<=routes.length;i++){}

// javascript says route undefined

}

How do I access the routes which is a array of arrays

4 Answers 4

2

Define routes outside the callback:

var routes;
jQuery.get('data/php/traces_pos.csv', function(data) { routes = jQuery.csv()(data); });
Sign up to request clarification or add additional context in comments.

1 Comment

Won't help because the callback has not yet run when the OP tries to use the variable.
1

You need to wait until routes has been set. I'm using a function and passing in routes as a parameter:

jQuery(document).ready(function() 
{

    jQuery.get('data/php/traces_pos.csv', function(data) {  
        var routes = jQuery.csv()(data); 
        performRoutes(routes);
    });
});

//if I use here 
function performRoutes(routes) {
    for (i=0;i<=routes.length;i++){
        // routes
    }
}

Comments

1

You have to define routes outside of either function, as such:

var routes;

jQuery(document).ready(function() 
{

    jQuery.get('data/php/traces_pos.csv', function(data) {  routes = jQuery.csv()(data); });

//if I use here 

for (i=0;i<=routes.length;i++){}

//  routes is no longer undefined

}

5 Comments

after doing that I get cannot read property length of 'undefined' in y browser
You want the length of undefined?
I am getting that error for this line - for (i=0;i<=routes.length;i++){}
yes it is. I get an array of arrays in firebug when I do console.log. But does that mean that it really doesnt have a property called length?
I would say this is now out of the scope of the question
0

Moving the declaration of routes outside the jQuery.get call will make it visible to your for loop -- but beware that your for loop runs before the callback is called, so routes will not have been set yet.

Anything you do that depends on the result of an asynchronous get must be either inside the callback function or in code that is called from within the callback function. In the latter case, you can pass your routes as a parameter at the function call -- there is no need to widen the variable's scope.

2 Comments

cant I just wait till the callback is finished? Otherwise my whole program which is dependent on routes will end up being in the jquery.get
The way to wait until the callback is called is to do your work inside the callback. That's what it's for. There's no good cross-browser supported way to block the thread until something happens in JavaScript. (Doing so would be likely to halt the entire JS engine).

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.