I want to retrieve a table from an SQL database dynamically into an array using JavaScript.
The code below works fine if I use a global JavaScript variable for the array. But I would like to pass the array the data is to be stored in dynamically as well. That is where the problem begins.
My source:
var getSQL = function (query, array, callback) {
var req = new XMLHttpRequest();
req.onreadystatechange = function () {
if (req.readyState == 4 && req.status == 200) {
callback(req.responseText, array);
}
};
var param = "?q=" + encodeURIComponent(query);
req.open("GET", "sql.php" + param, true);
req.send();
}
function mycallback (json_expr, t_array) {
t_array = JSON.parse(json_expr);
}
The custom array in which I want to stor ethe result of that request is called my_data
:
var my_data = [];
getSQL('SELECT * FROM users ORDER BY id', my_data, mycallback);
// wait some time
// then this code gets called via an onclick event
alert(my_data[0]['name']);
The result is undefined
. Why?