I tried to access a .txt file stored in the htdocs folder of my xampp installation using only Javascript and no PHP. I only intend to use ajax to process a text file stored in server. This is my javascript code to make an asynchronous request:
(function(global){
var ajaxUtils = {};
function getRequestObject(){
if(window.XMLHttpRequest){
return (new XMLHttpRequest());
}
else{
global.alert('Ajax is not supported!');
return(null);
}
}
ajaxUtils.sendGetRequest = function(requestUrl, responseHandler){
var request = getRequestObject();
request.onreadystatechange = function(){
handleResponse(request, responseHandler);
};
request.open("GET",requestUrl,true);
request.send(null);
}
function handleResponse(request, responseHandler){
console.log(request.readystate + " " + request.status);
if((request.readystate == 4) && (request.status == 200)){
responseHandler(request);
}
}
global.$ajaxUtils = ajaxUtils;
})(window);
This is how I passed parameters to ajaxUtils.sendGetRequest():
document.addEventListener("DOMContentLoaded", function(event){
document.querySelector("button").addEventListener('click', function(){
this.textContent='Said it!';
$ajaxUtils.sendGetRequest('http://localhost/ajax/file.txt',function(request){
var name = request.responseText;
var message = "<h2>Hello " + name + '!</h2>';
document.getElementById('content').innerHTML=message;
});
});
});
The code didn’t work and this is what I got in the console: request.readystate always returns ‘undefined’
‘readystate’ property of XMLHttprequest can have values 0,1,2,3, or 4, but here it always returns ‘undefined’. Does anybody know why this happened?