Well here's my problem. I have a function that is supposed to get a file and return the contents, cause my host provider doesn't let me use PHP.
function getStoryFromFile(file){
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (xhttp.readyState == 4 && xhttp.status == 200) {
return xhttp.responseText;
}
};
xhttp.open("GET", file, true);
xhttp.send();
}
And then I discovered that anonymous functions don't work like that. So then I tried to make it work by making it do this.
function getStoryFromFile(file){
var xhttp = new XMLHttpRequest();
var x = 'false';
xhttp.onreadystatechange = function() {
if (xhttp.readyState == 4 && xhttp.status == 200) {
x = 'true';
}
};
xhttp.open("GET", file, true);
xhttp.send();
if (x == 'true'){
return xhttp.responseText;
}
}
But that didn't work either. So I've tried to tweak it for hours and nothing's worked. All that I get is 'undefined'. So can somebody please explain to me why Javascript won't allow me to return the content the second way and why the developers of javascript made the language so goddamned difficult to understand. Thank you.
EDIT How do you get the callback function to write to a variable? I have:
function displayPage(){
file = 'story1.html' //Not actually like this in file, it changes based on database but i simplified it
var toHTML = '';
getStoryFromFile(file,function(text){
toHTML += text + "<br>";
});
document.getElementById('div').innerHTML = toHTML;
}
The anonymous function doesn't write even though it's global. Thats the main problem now