1

I need lines to be a global array but when I use console.log to compare values inside the function and outside the function, the inside one works fine but the outside one remains empty. Am I missing something here?

      var lines = new Array();
  $.ajax({
    type: "GET",
    url: "posts_replied_to.txt",
    success: function(content) {
      console.log("success");
      lines = content.split('\n');
      console.log(lines);
    },
    error: function() {
      console.log("error");
    }
  });
  console.log(lines);

4 Answers4

3

The problem here is not regarding global variables. Its the asynchronicity problem.By the time the console.log() outside your ajax request is called, the ajax success callback is not called.Thats why you won't get the right value.

async function doAjax() {
    return await $.ajax({
        type: "GET",
        url: "posts_replied_to.txt"
    });
}

let lines = await doAjax()
lines = content.split('\n')
console.log(lines)

Try this code using Async to get the expected result.

Kay
  • 1,266
  • 10
  • 21
0

Yes,AJAX is asynchronous function.So, in outside 'console.log(lines)' command run before AJAX.

You can AJAX asyn:false

What does "async: false" do in jQuery.ajax()?

ahmeticat
  • 1,899
  • 1
  • 13
  • 28
0

Before your GET response come your second console.log code also execute due to ajax is not async. Change as below,

var lines = new Array();
 $.ajax({
   type: "GET",
   url: "posts_replied_to.txt",
   async: false,
   success: function(content) {
     console.log("success");
     lines = content.split('\n');
     console.log(lines);
   },
   error: function() {
     console.log("error");
   }
 });
 console.log(lines);
Dui Samarasinghe
  • 247
  • 2
  • 10
0

Try using promise object returned by ajax call.

var lines = new Array();
  var promise_obj  = $.ajax({
        type: "GET",
        url: "posts_replied_to.txt"
  }).promise();

  promise_obj.done(function(response)
  {
    lines = response.split('\n');
    console.log(lines);
    // Rest of your logic goes here where you want to use lines.
  });
Vaibhav Patil
  • 132
  • 1
  • 6