Nienaber Nienaber - 1 month ago 11
Ajax Question

Fill external array in AJAX call

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.");
}
}

Answer

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.");
    }
}
Comments