Вот
так примерно стоит реализовывать чат на
XMLHttpRequestHTML<form action="" data-action="chat">
<input type="hidden" name="user" value="Вася">
<textarea name="message" cols="30" rows="10"></textarea>
<br>
<button type="submit">Отправить</button>
<div data-container="response"></div>
</form>
JSdocument.addEventListener('keydown', function (e) {
if (e.ctrlKey && e.keyCode == 13 && e.target.name == 'message') {
e.preventDefault();
sendMessage(e.target.form);
}
});
document.addEventListener('submit', function (e) {
if (e.target.dataset && e.target.dataset.action == 'chat') {
e.preventDefault();
sendMessage(e.target);
}
});
function sendMessage (form) {
var sendData = [];
for (var i = 0; i < form.elements.length; i++) {
if (form.elements[i].name && form.elements[i].value) {
sendData.push(form.elements[i].name + '=' + encodeURIComponent(form.elements[i].value));
}
}
if (sendData.length && form.message.value) {
var request = new XMLHttpRequest();
request.addEventListener('readystatechange', function (data) {
if (this.readyState == 4 && this.status >= 200 && this.status < 400) {
if (!form.response) {
form.response = form.querySelector('[data-container="response"]');
}
form.message.value = '';
//form.response.innerHTML = data.responseText;
form.response.innerHTML = 'Отправлено<br>' + sendData.join('&');
}
});
request.open('POST', form.action);
request.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
request.send(sendData.join('&'));
}
}