0

i have file.txt

apple     <--line 1 
banana    <--line 2

and this is my script

url = 'file.txt';
homelists = [];

$.get(url, function(data) {

  var lines = data.split("\n");    <--i want to split it by line

  $.each(lines, function(n ,urlRecord) {
    homelists.push(urlRecord);  <--add it to my homelists array
  });

});

console.log(homelists);   <-- returns array
console.log(homelists[0]);  <--undefined

my problem is i cant get the inside value of homelists how can i get homelists[0] or homelists[1]..(javascript or jquery(preferrable))

  • Maybe try `data.responseText.split("\n");`. What does `console.log(lines);` give you? – tanmay_garg May 24 '20 at 10:34
  • 1
    Does this answer your question? [How do I return the response from an asynchronous call?](https://stackoverflow.com/questions/14220321/how-do-i-return-the-response-from-an-asynchronous-call) – Robin Zigmond May 24 '20 at 10:38
  • In short, move those console.log statements inside the `$.get` – Robin Zigmond May 24 '20 at 10:40
  • yeah that will do..but i have a reason why i wanted it to accessed it outside so that i can use its value globally @Robin Zigmond.. thanks for that helpful link.... maybe ill try other alternative ways to call that array – vernie ruiz May 24 '20 at 12:10

3 Answers3

1

Javascript/Jquery ajax is an Async call meaning the code $.get and console.log on your example will be executed parallelly (immediate or the same times), so to parse the result of your file.txt, you need to do it inside the function (which will be executed after ajax called is done).

url = 'file.txt';
homelists = [];
$.get(url, function(data) {
  var lines = data.split("\n");  
  $.each(lines, function(n ,urlRecord) {
    homelists.push(urlRecord); 
  });
    console.log(homelists);  
    console.log(homelists[0]); 
});
Adam Mudianto
  • 71
  • 3
  • 13
  • Don't you think that it should affect it's value to the global variable? I mean even if they are Async the `homelists` variable must be affected after the process finishes! – Adnane Ar May 24 '20 at 10:45
  • Yes, `homelists` will be updated when the Ajax call is finished. But the OP is trying to access it before that. With asynchronous code, the execution order is no longer strictly top to bottom! – Robin Zigmond May 24 '20 at 10:48
  • Yes `homelists` is updated, you can try check the `homelists` using setTimeout, it will executed 5 second later, assuming your ajax called finish before 5 seconds: `setTimeout(function(){ console.log(homelists[0]) }, 5000);` – Adam Mudianto May 24 '20 at 10:55
0

I know this is too simple answer and may sound stupid to others but i have an idea! why not store in the session the $.get data

url = 'file.txt';
$.get(url, function(data) {
    localStorage['homelists'] = data;
});

then assign a variable to that session

homelists = localStorage['homelists'];

then make the session = null

localStorage['homelists'] = null

when you do console.log outside

console.log(homelists);      <-returns string which you can manipulate to turn it into array
console.log(localStorage['homelists']);  <-returns null

I dont know yet what could be the bad side/effect of this with my project.. any idea?

-1

Since you are using jQuery, It would be better if you use AJAX. !

const ImportData = function(file){

  let arrayData = undefined;
  
  $.ajax({
    url: file,
    type: 'GET',
    error: (err) => { throw new Error(err) },
    success: ( data ) => {
      arrayData = MakeArray( data );
      
      //Do whatever you want here
      
      console.log( arrayData );
      
    }
  });

}

const MakeArray = function(plaintext){

  const array = [];
  
  plaintext.split('\n').forEach( (line) => {
  
    line = line.trim();
    array.push( line );
  
  } );

  return array;

}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<script>

  const file = "https://www.w3.org/TR/PNG/iso_8859-1.txt";

  document.addEventListener('DOMContentLoaded', function(){
    
     ImportData( file );
    
  });

</script>
Adnane Ar
  • 683
  • 7
  • 11
  • It's irrelevant whether you use `$.get`, `$.ajax`, `fetch` or whatever - your example fails for exactly the same reason the OP's does. – Robin Zigmond May 24 '20 at 10:45
  • @RobinZigmond Could you please, give me some examples where my answer could fails? I just wanna correct myself? – Adnane Ar May 24 '20 at 10:47
  • Why not just try it yourself, with any contents whatsoever in `file.txt`. I guarantee it will fail. Similar questions are asked all the time here, and have been answered many times in the past - it's pointless writing the same answers again. Check the duplicate I put in the comments - I'm surprised no one else has yet voted to close this, but I'm sure it will happen soon. – Robin Zigmond May 24 '20 at 10:52
  • 1
    @RobinZigmond You were right! I just realised my mistake. The `to do code` should be inside the ajax call if we want it to work properly! – Adnane Ar May 24 '20 at 11:03