0

I have this JS file ...

  var my_data;

  function getData() {
      $.ajax({
          url: 'https://restcountries.eu/rest/v2/name/aruba?fullText=true',
          type: 'GET',
          async: false,
          success: handleData,
          error: showError
      });
  }

  // Process data returned from AJAX call
  function handleData(data) {
      my_data = data;
      console.log('my_data1', my_data);
  } // end function handleData

  console.log('my_data2', my_data);
  getData(); // Call function

When I run this function in console, I get

my_data2: undefined

my_data1: [{…}] (it returns an array)

I have read a lot about putting async:false to fix this issue. But its still not working. Why is my_data2 not returning an array ?

Slyper
  • 896
  • 2
  • 15
  • 32
  • 1
    you are logging my_data2 before the results of getData() have had a chance to set my_data – monty May 31 '18 at 02:54
  • Spot on @monty. Thanks mate. That was it .... – Slyper May 31 '18 at 02:56
  • @Tyler Roper - this is *not* a duplicate. The call to getData() was running synchronously (see async: false in ajax call). He just got the order wrong. I don't have enough cred to vote to reopen apparently, – monty May 31 '18 at 03:07
  • @CertainPerformance - this is not a duplicate - see commend above. – monty May 31 '18 at 03:07
  • Suffice to say that you should not be using `async: false` to "fix" this problem. Learn about callbacks instead and use them correctly. There is never a reason to make a synchronous "Ajax" call. – Felix Kling May 31 '18 at 05:24

2 Answers2

1

Yo are using async: false. But in your case, execution of statement console.log('my_data2', my_data); is is done firstly and then execute your ajax function, in that case it return undefined. Your code should be like this:

  var my_data;

  function getData() {
      $.ajax({
          url: 'https://restcountries.eu/rest/v2/name/aruba?fullText=true',
          type: 'GET',
          async: false,
          success: handleData,
          error: showError
      });
  }

  // Process data returned from AJAX call
  function handleData(data) {
      my_data = data;
      console.log('my_data1', my_data);
  } // end function handleData

  getData(); // Call function
  console.log('my_data2', my_data);

it will return array

g8bhawani
  • 674
  • 4
  • 8
0

swap these:

getData(); // Call *sync* function
console.log('my_data2', my_data);
monty
  • 1,543
  • 14
  • 30