0

i´m reading a text-file with jquery/ajax and convert it via the jquery/csv plugin.

This is my code:

var gotData;
function read() {
    $.get('text.txt', function(data) {
        var options = {"separator" : ";"};
        gotData = $.csv.toArrays(data, options);
        alert(gotData); //1
    }, 'text');
    alert(gotData); //2
}

Why is the data shown in alert 1 but not in alert 2? As I know the definition of the variable is global and should be shown, am I right? This leads to a even bigger problem because I want to access that data from my html-page (the .js is another file). So basically i want to get the variable which holds the data from my txt-file outside this function. Hope anyone can help. For further information please comment. Thank you in Advance.

Edit: The market duplicate doesn´t help me with my next problem, that I want to use that data in another .html-file to show it on my website.

y00
  • 1
  • 2
  • I run your code snippet but ... nothing happened. – hoangfin Nov 27 '18 at 07:58
  • Because second alert executed before `.get()` callback – Mohammad Nov 27 '18 at 07:58
  • That's because of asynchronous nature of the $.get, basically it gets called, and js immediately goes to alert, while the $.get isn't yet executed / values returned. – Goran.it Nov 27 '18 at 07:59
  • Because you need to read that text file first then you can have the data. – Just code Nov 27 '18 at 07:59
  • 1
    Possible duplicate of [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) – str Nov 27 '18 at 08:01
  • Thanks for your replies. And do you know how i get that data to another html file which includes javascript? --> to str : yea its a bit of a duplicate but my main question is how i get that data to another file – y00 Nov 27 '18 at 08:02

0 Answers0