I am writing a simple AJAX code as a way to learn the basics and introduce myself to the concepts. The following code grabs the contents of a textfile located on the server and passes to a variable, popping into an alert box.
My problem is that the code runs perfectly in the Eclipse IDE ‘Open with Web Browser’ but nowhere else.
var http = createRequestObject();
var responseContent;
function createRequestObject() {
var objAjax;
var browser = navigator.appName;
if(browser == "Microsoft Internet Explorer"){
objAjax = new ActiveXObject("Microsoft.XMLHTTP");
}else{
objAjax = new XMLHttpRequest();
}
return objAjax;
}
function getContent(name){
http.open('get', name);
http.onreadystatechange = function() {
if (http.readyState == 4) {
responseContent = http.responseText;
}
};
http.send(null);
}
$(document).ready(function() {
getContent('newcontent.txt');
alert(responseContent);
});
Does anyone know why this might be? Is there a problem with the code? If so, why would it work fine in eclipse but not elsewhere?
Thanks
Summarizing into a short answer:
The
XHRis sent in thegetContentfunction and a listener is attached.Then,
getContentreturns and the execution alerts the undefined variableresponseContent.At some point the XHR is answered, the
readyStatechanges to4and listener is called.It is only then that the
responseContentvariable is assigned.