I'm struggling to make this XMLHttpRequest work correctly. This is my first time using AJAX, so I'm not sure if I've formatted everything properly. I've searched all over the internet and found similar information and examples, but certain elements are in different orders, so I'm not sure which one is correct. I've tried them all, but nothing seems to work. Here's my code:
function ajaxRequest(){
var activexmodes=["Msxml2.XMLHTTP", "Microsoft.XMLHTTP"];
if (window.XMLHttpRequest){
return new XMLHttpRequest();
}
else if (window.ActiveXObject){
for (var i=0; i<activexmodes.length; i++){
try{
return new ActiveXObject(activexmodes[i]);
}
catch(e){
//suppress error
}
}
}
else{
return false;
}
}
function getData(fileName){
var fileLoc = encodeURI("assets/"+fileName+".html");
alert(fileLoc);
var request = new ajaxRequest();
request.open("GET", fileLoc, true);
var response = request.responseText;
alert(request.status);
alert(response);
request.send(null);
return response;
}
function home() {
var data = getData("home");
var contentDiv = document.getElementByClassName(content);
contentDiv.innerHTML = data;
}
home
is triggered when the user clicks on a div in the page. I know that getData
is being accessed because the alerts pop up, however I get a status code of 0. This happened on both my local machine and on a live server. I read that localhosts can throw a 0 status regardless of the actual status but it's happening on a live server as well. If someone could help me fix this issue and/or clarify the correct order of events in the function, I would greatly appreciate it.
EDIT: new code:
function getData(fileName){
fileLoc = encodeURI("assets/"+fileName+".html");
alert(fileLoc);
request.onreadystatechange = processData;
request.open("GET", fileLoc, false);
request.send();
alert(request.readyState);
alert(response);
}
function processData(){
if (request.readyState == 4){
if (request.status == 200){
document.getElementsByClassName('content').innerHTML = request.responseText;
}
else{
alert("An error has occurred making the request");
}
}
}