function loadChat() {
    ajaxGetRequest("/chat", displayChat);
}

function displayChat(response) {
    let chat = "";
    for(let data of JSON.parse(response)){
        chat = chat + data.message + "</br>";
    }
    document.getElementById("chat").innerHTML = chat;
}

function sendMessage(){
    let messageElement = document.getElementById("message");
    
    let message = messageElement.value;
    messageElement.value = "";
    let toSend = JSON.stringify({"message": message});

    ajaxPostRequest("/send", toSend, displayChat);
}

function ajaxGetRequest(path, callback) {
    let request = new XMLHttpRequest();
    request.onreadystatechange = function() {
        if (this.readyState === 4 && this.status === 200) {
            callback(this.response);
        }
    };
    request.open("GET", path);
    request.send();
}


function ajaxPostRequest(path, data, callback) {
    let request = new XMLHttpRequest();
    request.onreadystatechange = function() {
        if (this.readyState === 4 && this.status === 200) {
            callback(this.response);
        }
    };
    request.open("POST", path);
    request.send(data);
}