0

I have a javascript function. It looks like this

function open_file (filename) {
  'use strict';
  var file;
  $.ajax(filename, {
    dataType: 'text',
    success:  function (data) {
      file = data;
      alert(file);
    }
  });
  return file;
}

The alert displays the text that is being stored in the file, just like I want it to. However, when it is time to return the value to the function caller, it returns an undeclared value.

How can I set the value of a variable using jQuery, but with the variable's value to be used outside of jQuery?

EDIT: I've read the duplicate question, but I'm still confused about how the call back is working as I try to trace it through the call stack. I will keep working on trying to sort this mess out.

  • Far better duplicate and canonical answer http://stackoverflow.com/questions/14220321/how-do-i-return-the-response-from-an-asynchronous-call – charlietfl May 15 '16 at 03:40
  • Dear humans of the future. I'm the one who asked this question, and @charlietfl has provided the link that helped me. You should click on it. – Travis Rigg May 15 '16 at 03:44

1 Answers1

0

Try this :

function open_file (filename) {
  'use strict';
 return  $.ajax(filename, {
    dataType: 'text'
  });

}
bob
  • 4,595
  • 2
  • 25
  • 35