0

I'm new to javascript and jquery, trying to learn, here I have this code to push values into the array, when I tried use length it shows me 0.

I know that there is guide out there, but still I don't understand what it actually means, can anyone help me out?

$.ajax({
            url : "pokemonlist.txt",
            dataType: "text",
            success : function (data) {
        var lines = data.split('\n');

        for(var i=0;i<lines.length;i++) {
            var arr = lines[i].split('"');

            pokemon_id = arr[1];
            pokemon_img = arr[3];
            pokemon_name = arr[4];
            pokemon_name = pokemon_name.trim()

            pokemon_array.push([ pokemon_id, pokemon_img, pokemon_name ]);
        }
            }
        });

    console.log(pokemon_array.length);
MuthaFury
  • 805
  • 1
  • 7
  • 22
  • 1
    console.log is outside the $.ajax call, so it occurs before success function completes. Try `setTimeout(function(){console.log(pokemon_array.length); }, 1000);` or move the console log inside the success function, at the end. – mkaran Aug 18 '16 at 08:48
  • timeout is not a solution, it is just a test and I suggested it just to see what will happen so that it is more clear to MuthaFury how all this works :) – mkaran Aug 18 '16 at 08:53

2 Answers2

1

You're calling console.log(pokemon_array.length) outside of the success callback, so it's actually called before the ajax call is done.

maxdec
  • 5,707
  • 2
  • 30
  • 35
-1

Here http://api.jquery.com/jquery.ajax/

Read about success and complete parameters.

Simple example:

$.ajax({
    url: 'my-mega-link',
    success: function (data) {
        console.log(data);
    }
});
ventaquil
  • 2,780
  • 3
  • 23
  • 48
  • While this link may answer the question, it is better to include the essential parts of the answer here and provide the link for reference. Link-only answers can become invalid if the linked page changes. - [From Review](/review/low-quality-posts/13377759) – dakab Aug 18 '16 at 09:26
  • @dakab But documentation is the best answer for simple questions :( – ventaquil Aug 18 '16 at 10:25
  • Sure it is. But if the documentation isn't available, it renders a link-only answer useless. Prociding a simple example (like the one [you added](http://stackoverflow.com/posts/39013761/revisions)) makes it much more helpful. – dakab Aug 18 '16 at 11:40
  • @dakab okay I will remember this advice :) – ventaquil Aug 18 '16 at 12:16