skip to Main Content

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


  1. 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:

    let myarr = [];
    
    function doStuff(arr) {
      arr = [1, 2, 3];// your approach that doesn't work
    }
    doStuff(myarr);
    console.log('After doStuff', myarr)
    
    function doStuff2(arr) {
      arr.push(...[1, 2, 3]);// update the array object instead
    }
    doStuff2(myarr);
    console.log('After doStuff2', myarr)

    A more modern approach would be to return the $.ajax promise

    var myArray = [];
    
    function doThis(endpoint) {
       return $.getJSON(api_url + endpoint, {api_key: api_key}); 
    }
    
    doThis(someEndpoint).then(data=>{
      // do stuff with data and also store in global
      myArray = data.keyname
    });
    
    Login or Signup to reply.
  2. 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

    Login or Signup to reply.
    1. Make sure that data.keyname has something valid
    2. You are assigning the array to a new object so the argument array now
      points to the new object and the myArray still is at []. You can pass an object whose one attribute is an
      array, 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
    const api_url = 'some-url';
    const api-key = 'some-key';
    var myObject = {array:[]};
    
    function doThis(endpoint, obj) {
      $.ajax({
        'url': api_url + endpoint,
        'method': 'get',
        'data': {
          'api_key': api_key,
        },
        'success': function(data) {
          /*store data in global variable for later use*/
          obj.array = data.keyname;
          success();
        },
        'error': function() {
          console.log('ajax error');
        },
      });
    }
    
    doThis(someEndpoint, myObject);
    
    
    
     function success(){
        console.log(myObject.array);    
    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search