I have a function with two parameters that I need to correctly make an ajax call and process the results, as this function is called two times and with different arguments.
What I’m trying to accomplish is to overwrite the global variable myArray
with the data I get from the Ajax call.
const api_url = 'some-url';
const api-key = 'some-key';
var myArray = [];
function doThis(endpoint, array) {
$.ajax({
'url': api_url + endpoint,
'method': 'get',
'data': {
'api_key': api_key,
},
'success': function(data) {
/*store data in global variable for later use*/
array = data.keyname;
},
'error': function() {
console.log('ajax error');
},
});
}
doThis(someEndpoint, myArray);
What the rest of the success function (not included) does is it uses the Handlebars.js library to print a few options in a select, so once that’s been drawn correctly I am 100% sure that the Ajax call has returned.
I was under the impression that passing an empty array as an argument would’ve allowed me to use the parameter inside the function to act on the empty array itself. But if I try to console.log(myArray)
even after the select has been drawn, I’m still left with an empty array and I cannot figure out why, as the assignment happens inside the success function that is triggered once the call has returned, so this shouldn’t be a matter of asynchronicity.
I also tried to use return array
at the end of both the ajax call and the outer function, but that still had no effect.
Eta: data.keyname
returns an array of objects.
3
Answers
I suspect that you are assuming that assigning the value as a new array to the parameter inside the function will update the value of the variable passed into the function. This is not the case.
Push the new data into the array reference represented by the parameter instead
Simplified example:
A more modern approach would be to return the $.ajax promise
You not using Array correctly. Ajax should return data in json, which you will store in some variable. You then parse and convert to array again incase you need it as array. So you should JSON.parse(data.keyname) in success statement. I am assuming data is coming in json format. Learn more about JSON.parse here https://www.w3schools.com/js/js_json_parse.asp
data.keyname
has something validarray
nowpoints to the new object and the
myArray
still is at[]
. You can pass an object whose one attribute is anarray, object’s array key will point to the new array that you can access
like –
console.log(myObject.array);
also this needs be done only after the Ajax is done as ajax call an async function