1

I am trying to get a variable out of a function. This function includes a $.get() function inside. Here is the code:

$(function () {
  var valiable = '';
  function functionName(string) {
      var file = "lang.txt";
      $.get(file, function (txt) {
          var lines = txt.split("\n");
          for (var i = 0, len = lines.length; i < len; i++) {
              if ($.trim(lines[i]) == string) {
                  valiable = lines[i];
              }
          }
      });
      return valiable;
  }

  $('#button').on('click',function () {
   var variable = functionName(string);
   console.log(variable);
   });

});

I'm trying to parse a .txt file to get its content.

Anonymouse
  • 19
  • 5

2 Answers2

0

$.get() is asynchronous, so you could just save the contents into the an output variable in its success handler. Then, just access this stored value from the button click handler. In this case, you'll execute the function loading of the page. This has the drawback, that the data could not be ready when clicking onto the button and also, you need to reload the page to fetch the data again.

$(function () {
  var output = '';

  function functionName() {
      var file = "lang.txt";
      $.get(file, function(txt) {
          var lines = txt.split("\n");
          output = lines.join("");
      });
  }
  functionName();

  $('#button').on('click', function () {
      console.log(output);
  });

});

If you want to execute the file loading on click onto a button, you can pass a success handler function (callback) as an argument. The successHandler function then has an argument with the data and is called after $.get() is executed. So, you can define in the button click listener, what should happen with the loaded data.

$(function () {
  function functionName(successHandler) {
      var file = "lang.txt";
      $.get(file, function(txt) {
          var lines = txt.split("\n");
          var output = lines.join("");
          successHandler(output);
      });
  }

  $('#button').on('click', function() {
      functionName(function(data) {
         console.log("this is the data: " + data);
      });
  });

});
ssc-hrep3
  • 15,024
  • 7
  • 48
  • 87
0

That call is async, you are not able to return a value fast enough from that ajax call. What you should do is add a callback to your method

function fn(callback) {
    var value;
    $.get('lang.txt', function(data) {
        ... 

        callback(value)
    });
}

And now you can append a callback to the method

fn(function(value) {
  console.log(value);
});
Shane
  • 3,049
  • 1
  • 17
  • 18