I use the following code :

function createXHR() {
var request = false;
try {
request = new ActiveXObject('Msxml2.XMLHTTP');
}
catch (err2) {
try {
request = new ActiveXObject('Microsoft.XMLHTTP');
}
catch (err3) {
try {
request = new XMLHttpRequest();
}
catch (err1) {
request = false;
}
}
}
return request;
}

function sendRequest() {
var validate=document.getElementById('validate').value;
querystring = 'validate=' + validate;
xhr.open('POST', 'validate.php', true);
xhr.onreadystatechange = sayHello;
xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
xhr.send(querystring);
}


function sayHello() {
if (xhr.readyState == 4) {
//return answer
}
}

xhr = createXHR();


this code sometimes works and sometimes doesn't work.
how we can sure that above code works?