function g(i) { return document.getElementById(i) }; var xhttp, updateTime, reqTime, reqFin; var msgList = document.getElementById('msgs'); g('cmdInput').addEventListener("keyup", function(event) { event.preventDefault(); if (event.keyCode === 13) { sendCmd(); } }); function sendCmd() { var form = g('cmdForm'); msgList.innerHTML += 'Sent: ' + g('cmdInput').value + '\n'; g('cmd').value=g('cmdInput').value; g('cmdInput').value=''; g('cmdInput').value = ''; msgList.scrollTop = msgList.scrollHeight; return transmit(form); } var lastMsgIndex=0; function transmit(f) { if (!xhttp) { reqTime = 0; reqFin = false; xhttp = new XMLHttpRequest(); xhttp.timeout = 1000; xhttp.overrideMimeType("text/plain"); xhttp.open('POST', 'webcsapi'); xhttp.send(f ? (new FormData(f)) : ''); xhttp.onreadystatechange = function () { if (xhttp.readyState === XMLHttpRequest.DONE && xhttp.status === 200) { var data = xhttp.responseText.split("\n"); for(i=0; i < data.length; i++) { var numEnd = data[i].indexOf("}"); var num = parseInt(data[i].substring(1, numEnd)); var msg = data[i].substring(numEnd+1); if(num > lastMsgIndex || lastMsgIndex == 0) { msgList.innerHTML += msg; msgList.scrollTop = msgList.scrollHeight; lastMsgIndex = num; } } xhttp = null; updateTime = 0; reqFin = true; } else { if(!reqFin && reqTime > 10) { xhttp = null; reqFin = true; } } } } return false; } transmit(); setInterval(transmit, 2000);