Slyper
Slyper

Reputation: 906

JS Global Variable not working

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 ?

Upvotes: 0

Views: 60

Answers (2)

g8bhawani
g8bhawani

Reputation: 674

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

Upvotes: 1

monty
monty

Reputation: 1590

swap these:

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

Upvotes: 0

Related Questions