0

I am trying to write a generic function which will fill any array I pass in with data from the server. The code below does fill the array within the function properly, but when I try to pass in the 'characters' array it won't take it.

Here is the function call:

$(document).ready(function() {
    databaseConnect("loadCharacter.php", characters);
    document.write(characters[0]); //This spits out 'undefined'
});

And here is the function:

function databaseConnect (file, array) {
    if (login == true) {
        $.ajax({
            type: "POST",
            url: file,
            data: {id : identi},
            success: function(data, array) {
                array = data.split('-');
                i = 0;
                while(array[i]) {
                    array[i] = JSON.parse(array[i]);
                    ++i;
                }
            },
        });
    } else {
        document.write("Dude. You're not logged in.");
    }
}
Nienaber
  • 101
  • 1
  • 2
  • 12
  • never use `document.write`. if you use it after the page has initially loaded it will overwrite the entire page with the content you want to write. That means all the content and assets. – synthet1c Oct 15 '16 at 18:55
  • 2
    http://stackoverflow.com/questions/23667086/why-is-my-variable-unaltered-after-i-modify-it-inside-of-a-function-asynchron – epascarello Oct 15 '16 at 18:58

1 Answers1

1

You need to understand how asynchronicity works. Your code executes like this:

  1. databaseConnect is called
  2. the ajax call is sent to the server
  3. databaseConnect function returns control to the main $.ready() function
  4. document.write is called - yet at this point there's nothing in the characters array. Executing the first 4 steps takes at most tens of microseconds, whereas an ajax response from the server takes a lot longer to return.
  5. ...much later - the ajax returns and populates the characters array.

You should make use of the callback, as such

$(document).ready(function () {
    databaseConnect("loadCharacter.php", processCharacters);
});

function processCharacters (characters) {
    document.write(characters[0]); 
}

function databaseConnect (file, callback) {
    if (login == true) {
        $.ajax({
            type: "POST",
            url: file,
            data: {id : identi},
            success: function(data, array) {
                var array = data.split('-');
                i = 0;
                while(array[i]) {
                    array[i] = JSON.parse(array[i]);
                    ++i;
                }

                callback(array);
            },
        });
    } else {
        document.write("Dude. You're not logged in.");
    }
}
motanelu
  • 3,945
  • 1
  • 14
  • 21