You're actually merging the arrays correctly and both methods would work (provided like others said that you use the return value of concat
), but the result is empty because you're doing it when the answers from the ajax requests didn't arrive yet and the arrays are still empty.
When making ajax requests you must manipulate the result inside the success callback function, not at the same level of the ajax request code; for example
var myvec = [];
$.getjson(request_url, function(data) {
myvec = data;
});
process(myvec);
will NOT work, because it's attempting to use the content of myvec
right after the request has been submitted but before the reply arrived. Correct code is instead:
$.getjson(request_url, function(data) {
// This code is executed when the data arrives from the server
process(data);
});
If you need to concatenate the results of two async queries you must either chain them (make the second query only once the first returned) or you must wait for the second one to complete:
// First solution, simple but slower (waits for first reply
// before making second request)
$.getjson(request_url_1, function(data_1) {
$.getjson(request_url_2, function(data_2) {
process(data_1.concat(data_2));
});
});
or
// Second solution; starts both requests and waits for both
// of them to complete before doing the processing
var count = 0;
var res = [];
function handle_data(data) {
res = res.concat(data);
count += 1;
if (count == 2) {
process(res);
}
}
$.get(request_url_1, handle_data);
$.get(request_url_2, handle_data);
This crazy guess is simply coming from the frequency that this kind of error has in beginner code.