// Chat Homework function jsonPost(url, data) { return new Promise((resolve, reject) => { var x = new XMLHttpRequest(); x.onerror = () => reject(new Error('jsonPost failed')) //x.setRequestHeader('Content-Type', 'application/json'); x.open("POST", url, true); x.send(JSON.stringify(data)) x.onreadystatechange = () => { if (x.readyState == XMLHttpRequest.DONE && x.status == 200) { resolve(JSON.parse(x.responseText)) } else if (x.status != 200) { reject(new Error('status is not 200')) } } }) } let login = document.getElementById('nick') let msg = document.getElementById('msg') let send = document.getElementById('send') let chat = document.getElementById('chat') function sendMessage() { const newMsg = jsonPost("http://students.a-level.com.ua:10012", { func: 'addMessage', nick: login.value, message: msg.value }) newMsg.then(data => console.log(data.nextMessageId)) } function getMessages() { jsonPost("http://students.a-level.com.ua:10012", { func: "getMessages", messageId: 0 }).then((a) => { showMsg(a.data, chat) }) } send.onclick = () => { return sendMessage(), getMessages() } function showMsg(data, container) { let sortedData = data.sort((a, b) => b.timestamp - a.timestamp) for (let message of sortedData) { let div = document.createElement('div') let spanName = document.createElement('span') let spanMsg = document.createElement('span') let spanTime = document.createElement('span') let time = new Date(message.timestamp) container.appendChild(div) div.appendChild(spanName) div.appendChild(spanMsg) div.appendChild(spanTime) spanName.innerHTML = message.nick + ' : ' spanMsg.innerHTML = message.message + ' ' spanTime.innerHTML = time } } setInterval(getMessages, 3000)