Attempting to read a local file on the server using the standard loadDoc(url, cfunc) function, my goal is to:
1) Search for a specific string in the file (getLine());
2) If possible, save that line to a variable.
For point 1, I provide a string to the callback. 2) The challenge arises when trying to retrieve the response due to the asynchronous nature of XMLHTTPRequest. Currently, the error encountered is: "ReferenceError: xhttp is not defined"
function main(){
var url="data.txt"
var str="1,0,"; //just an example
var myCallBackWithVar = function(){
getLine(str);
};
loadDoc(url, myCallBackWithVar);
//Any way to obtain the line here?
}
function loadDoc(url, cfunc) {
var xhttp=new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (xhttp.readyState == 4 && xhttp.status == 200) {
cfunc(xhttp);
}
}
xhttp.overrideMimeType('text/plain');
xhttp.open("GET", url, true);
xhttp.send();
}
//Locate string with desired data in txt file
function getLine(str) {
var data=xhttp.responseText;
//Locate the line in the txt file
var start=data.indexOf(str);
var end=data.indexOf(";",start);
var line=data.substring(start,end);
return line;
}
data.txt resembles the following:
some data here
0,0,9;
1,0,10;
1,1,11;
I have previously attempted to pass the XMLHTTPRequest object getLine(xhttp,str). How can I address points 1 and 2 effectively? I prefer to avoid using jQuery at this time. Thank you