So I have started a project, where I want to make an online ajax chat, but I do NOT want to use jQuery JSON, COMET and so on. I am looking for pure javascript, no libraries no framework.
Good news is that I have already made the chat and it is working fine. Why do i make this post? Because I simply cannot find any pure javascript solution for long-polling. Currently I am using the setInterval method to "ask" the database to send whatever is in the database. now, how do I execute my ajax request whenever I get a response? (Long-polling).
please bear in mind that I am not looking for a jQuery solution or what have you.. I am using pure JavaScript and PHP. No framework or library.
Thanks in advance.
i believe this is relatively close to what your looking for - referencing a vanilla js ajax tutorial on nettuts plus:
load('test.txt', function(xhr) {
document.getElementById('container').innerHTML = xhr.responseText;
// you would obviously custom tailor this peice to utilize your specific data
});
function load(url, callback) {
var xhr;
if(typeof XMLHttpRequest !== 'undefined') xhr = new XMLHttpRequest();
else {
var versions = ["MSXML2.XmlHttp.5.0",
"MSXML2.XmlHttp.4.0",
"MSXML2.XmlHttp.3.0",
"MSXML2.XmlHttp.2.0",
"Microsoft.XmlHttp"]
for(var i = 0, len = versions.length; i < len; i++) {
try {
xhr = new ActiveXObject(versions[i]);
break;
}
catch(e){}
} // end for
}
xhr.onreadystatechange = ensureReadiness;
function ensureReadiness() {
if(xhr.readyState < 4) {
return;
}
if(xhr.status !== 200) {
return;
}
// all is well
if(xhr.readyState === 4) {
callback(xhr);
}
}
xhr.open('GET', url, true);
xhr.send('');
}
and you could build your "success" handlers into the 'ensure readiness' based on the return values