0

I have some javascript array that I append within a function and call after the function has run (the db information is a call to CouchDB):

$(document).ready(function() {

  my_array = [];

  view_name = db_name+'/farms_by_name'
  $db.view(view_name, {
    success: function(data) {
       console.log(data)
       for (i in data.rows) {
           console.log(data.rows[i]);
           plot_name.push(data.rows[i].value.name);
           my_array.push("0");
           console.log(my_array)
           console.log(my_array.length)
        }
    },
    error: function(e) {
      alert('Error loading from database: ' + e);
    }
  });

  console.log(my_array);
  console.log(my_array.length);

});

Using firebug, I see that within the function the array is appended correctly, for e.g. a single element the console.log returns

my_array = ["0"]
my_array.length = 1

but the console.log after the function (which appears first in the firebug log) shows:

my_array = [ ]
my_array.length = 1

and my_array when inspected in the log reveals:

[ ]
0              "0"

Can anyone explain this behaviour to me and explain how I should correctly append the array such that I can call the length and loop through it correctly outside of the db success function?

Thanks!

1
  • 2
    Obviously it is being executed asyncronously Commented May 4, 2012 at 10:50

2 Answers 2

1

zerkms is right: the variable is being altered inside a success callback function. add a second function in the $(document).ready function called -say- logAfterSuccess

function logAfterSuccess()
{
    console.log(my_array);
    console.log(my_array.length);
}

and simply call that function from within the success callback:

success: function()
{
    //code goes here
    logAfterSuccess();
}

That should give you the expected result

Sign up to request clarification or add additional context in comments.

3 Comments

OK, so then if I have multiple polls of the database using Ajax, with my main javascript code relying on each query returning a success status, then I'll need to nest the functions within each other....
(I mean each query returning a success, but only after the previous success)
Not really, you could set the async option to false, making the script execution wait for a the respons
0

The last two console.log will always return [] and 0 because you are checking the array outside of the callback function, if you move the check to inside the callback function you should get your desired results.

For example:

$(document).ready(function() {

  my_array = [];

  view_name = db_name+'/farms_by_name'
  $db.view(view_name, {
    success: function(data) {
       console.log(data)
       for (i in data.rows) {
           console.log(data.rows[i]);
           plot_name.push(data.rows[i].value.name);
           my_array.push("0");
           console.log(my_array);
           console.log(my_array.length);
        }
        afterArrayPopulated(my_array);
    },
    error: function(e) {
      alert('Error loading from database: ' + e);
    }
  });
});

function afterArrayPopulated(arr){
  console.log(arr)
  console.log(arr.length)
}

6 Comments

the variable is declared in the $(document).ready function, the issue isn't the scope as such, rather than the asynchronous behaviour of the success callback function
I would also place the my_array variable outside of the $(document).ready function
There is no need to pass my_array to the afterArrayPopulated function, as it will have access to my_array directly. PS: it's considered bad manners to take suggestions others made and not crediting them for it, like you obviously did.
There is no need to pass my_array to the function as my_array is in the global scope, however to make this function reusable I would pass an array to the function thus allow you to use any variable names you want, as for taking others suggestions I do not feel I have as I commented on my own code prior to seeing your comment.
@EliasVanOotegem you mean my code, if you had noticed the time, you would have seen that my answer was prior to yours, so to refer to your comment, why are you making suggestions that I have already produced answers for?
|

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.