Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
172
rated 0 times [  179] [ 7]  / answers: 1 / hits: 21233  / 13 Years ago, tue, june 14, 2011, 12:00:00

I'm trying to load data from a text file on my server using the $.get() function in an external script file. My code is as follows:



  /* 
* Load sample date
*/
var stringData;
$.get(http://localhost/webpath/graphing/sample_data.txt, function(data){
stringData = data;
//alert(Data Loaded: + stringData);
});
//Split values of string data
var stringArray = stringData.split(,);
alert(Data Loaded: + stringData);


When I'm inside the $.get() function I can see stringData var get peopulated just fine and the call to alert confirms that it contains data from the sample text file. However, when I get outside the $.get() function, the stringData var no longer shows. I don't know enough about how the function works to know why it is not doing as I expected. All I want it to do is load the text data into a variable so I can work with it. Any help is appreciated.


More From » jquery

 Answers
28

get is asynchronous meaning it makes a call to the server and continues executing the rest of the code. This is why you have callback methods. Whatever you intend to do with the return data do it inside the callback method(where you have put the alert).



get, post are all asynchronous. You can make a synchronous call by using




  1. using $.ajaxSetup({ async: false }); anywhere in your code. This will affect all ajax calls in your code, so be careful.


  2. $.ajax with async: false e.g. shown below.




Look at the below code and the API docs link mentioned above to fix your problem.



  /* 
* Load sample date
*/
var stringData = $.ajax({
url: http://localhost/webpath/graphing/sample_data.txt,
async: false
}).responseText;

//Split values of string data
var stringArray = stringData.split(,);
alert(Data Loaded: + stringData);

[#91730] Saturday, June 11, 2011, 13 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
devonw

Total Points: 311
Total Questions: 116
Total Answers: 111

Location: Senegal
Member since Fri, Aug 21, 2020
4 Years ago
;