(noob alert) Sup guys. I'm an extreme beginner and this will be my first question so I'd be grateful if someone could lend me a hand with this. I just started learning express today and I'm not sure yet where to put what but I'm pretty sure that's why this isn't working properly. It only returns message = "" and inserts a blank into the database instead of the message typed inside the textarea. Sorry for the noob question
const express = require('express')
const path = require('path')
const app = express()
const mysql = require("mysql")
const bodyParser = require('body-parser');
const connection = mysql.createConnection({
host: "localhost",
user: "root",
password: "......",
database: "chat_database"
})
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
app.use(express.static(path.join(__dirname, "public")))
app.listen(3000)
app.post('/', (req, res) => {
const data = req.body.message
console.log(data);
let sql = `INSERT INTO chats(content) VALUES (?)`
connection.query(sql, [data], (err, result) => {
if (err) throw err
console.log(result);
console.log("data has been successfully inserted into the database!");
})
})
const mainChatBlock = document.querySelector("#main-chat-block")
const mainInputArea = document.querySelector("#main-input-area")
const mainSendButton = document.querySelector("#main-send-button")
mainSendButton.addEventListener("click", () => {
let newMessage = document.createElement("div")
newMessage.innerHTML = mainInputArea.value
mainChatBlock.append(newMessage)
mainInputArea.value = ""
mainChatBlock.scrollTop = mainChatBlock.scrollHeight
})
mainInputArea.addEventListener("keyup", function(event) {
if (event.keyCode === 13) {
event.preventDefault();
mainSendButton.click();
}
});
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
<title>my chat</title>
<link rel="stylesheet" href="css/style.css">
</head>
<body>
<main>
<div id="outermost-main-div">
<div id="outermost-chat-div">
<div id="main-chat-area">
<div id="main-chat-block">
</div>
</div>
<form action="/" method="post" id="outer-input-area">
<textarea name="message" id="main-input-area" placeholder=">>> Enter your message here"></textarea>
<button type="submit" id="main-send-button">Send</button>
</form>
</div>
</div>
</main>
<script src="script.js"></script>
</body>
</html>
CodePudding user response:
I figured it out guys. turns out the culprit was the clear value in the client side js mainInputArea.value = ""
but to clear the entry, I did something like this
mainSendButton.addEventListener("click", () => {
let newMessage = document.createElement("div")
newMessage.innerHTML = mainInputArea.value
mainChatBlock.append(newMessage)
mainChatBlock.scrollTop = mainChatBlock.scrollHeight
setTimeout(del, 100)
})
function del() {
mainInputArea.value = ""
}