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 ?

5
  • 1
    you are logging my_data2 before the results of getData() have had a chance to set my_data Commented May 31, 2018 at 2:54
  • Spot on @monty. Thanks mate. That was it .... Commented May 31, 2018 at 2: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, Commented May 31, 2018 at 3:07
  • @CertainPerformance - this is not a duplicate - see commend above. Commented May 31, 2018 at 3: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. Commented May 31, 2018 at 5:24

2 Answers 2

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

Sign up to request clarification or add additional context in comments.

Comments

0

swap these:

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.