2

If I copy and paste each part of this function everything works. However when I try to use the function on its own I get:

VM7192:4 Uncaught TypeError: Cannot read property 'match' of undefined

My function is:

var read_f = function() {
    var restext = $.get('file.txt');
    var text = restext.responseText;
    text = text.match(/[a-zA-Z0-9]/g);
    text = text.join('').split(/Q0/);
    return text;
};

What's happening ?

atomsmasher
  • 725
  • 8
  • 20
  • 2
    `$.get` returns a [jqXHR](https://api.jquery.com/jQuery.ajax/#jqXHR) object. Such an object doesn't have a `responseText` property. Hence `text` is `undefined` and `undefined.match()` throws an error because `undefined` doesn't have such a method. – Felix Kling Oct 04 '16 at 17:00
  • 4
    `$.get` uses AJAX. AJAX is *asynchronous*. You cannot return a value from an AJAX call. You need to use callbacks. – gen_Eric Oct 04 '16 at 17:00
  • @FelixKling not sure I understand...for example, this doesn't work out for me https://jsfiddle.net/gf8pq135/ – atomsmasher Oct 04 '16 at 18:12
  • The first argument passed to `success` is already the response text, so you need `var textres = data;` or directly access `data`. See the documentation: https://api.jquery.com/jquery.ajax/ – Felix Kling Oct 04 '16 at 18:14

0 Answers0