0

I am making a website that requires for it to read a value from a .txt file(which for testing purposes was set to "8080") to then store that value into a global variable. Here is the code that I'm having issues with:

var portTxtFile = "/assets/port.txt";
var portTxtData;
jQuery.get(portTxtFile, function(data) {
  console.log(data);
  portTxtData = data;
});
console.log(portTxtData);

The console logs were added to test if the variable was really being set. Here are the results of the console logs:the console

For some reason, the console is logging the console.log(portTxtData) outside of the jQuery.get function before the console.log(data) that's inside the function. And the variable "portTxtData" is not being set.

I need help setting the variable "portTxtData" to "data" from the "jQuery.get" function.

Hashim
  • 45
  • 2
  • 3
  • 9
  • Use .ajax() instead of .get() please see the example https://stackoverflow.com/questions/23283276/execute-function-after-ajax-call-is-complete/23283596#23283596 – Naveen Chandra Tiwari Jun 16 '17 at 12:08
  • @NaveenChandraTiwari — `ajax()` is the same as `get()` but with slightly different defaults. Using it brings no benefit. – Quentin Jun 16 '17 at 12:11
  • @NaveenChandraTiwari — That example is dreadful. It uses `async: false` which is known to cause performance problems and which browsers have deprecated. – Quentin Jun 16 '17 at 12:11
  • @Quentin if you want to run your code that way you have to use async. If you want to do it in `a proper` way I recommend you learning the basics of async functions, function callbacks and ajax. The `console.log(portTxtData);` triggers before the other one because jQuery.get is async – nicowernli Jun 16 '17 at 12:13
  • @Hashim You can avoid async false and perform your action in complete:function(). – Naveen Chandra Tiwari Jun 16 '17 at 13:17

0 Answers0