So I am now working on learning node.js servers with socket.io, and having the form submitted would recreate a new web socket connection. I have read that it could be fixed using jQuery to alter the submit action of the form in order to not have it refresh the page, but right now I just want to see if it could be done without jQuery or AJAX. my html looks like this:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Socket</title>
</head>
<body>
<script src="/socket.io/socket.io.js"></script>
<form id="form" onsubmit="" action="">
<input name="message" id="message" type="text" placeholder="message" autocomplete="off">
<input id="send" type="submit">
</form>
<script type="text/javascript" src="js/main.js"></script>
</body>
</html>
where main.js :
const socket = io.connect('83.130.85.31:7776');
const button = document.getElementById("send");
const message = document.getElementById("message");
const form = document.getElementById("form");
const sendMessage = (event) => {
socket.emit("message", {message: message.value});
message.value = "";
};
form.addEventListener("submit", sendMessage)
socket.on("message", (data) => {
console.log(data.message);
})
I know my code is very naive, I just focus on understanding implementation of socket.io right now and it was a small test.