I was doing a chat project in php, with ajax, but my code does not insert anything into the database, but I have no idea what it is, and before they think I did not search, I already tried to bring the variable from js to php, but I could not, I tried to change the sql command, but neither was it. So I've come to ask for your help, it's not chewed, because I already did, that's just the problem. (The bank does not populate).
Thanks in advance for your attention.
index.php
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Sistema de Chat</title>
<link rel="stylesheet" href="style.css"/>
<script src="https://code.jquery.com/jquery-3.3.1.js"integrity="sha256-2Kok7MbOyxpgUVvAk/HJ2jigOSYS2auK4Pfzbm7uH60="
crossorigin="anonymous">
</script>
</head>
<body>
<?php
session_start();
$_SESSION['username'] = "Henrique Nunes";
?>
<div id="tela">
<h1>Bem vindo ao chat</h1>
<div class="tela_chat">
<div id="chat">
</div>
<form method="POST">
<textarea name="mensagem" cols="30" rows="7" class="textarea">
</textarea>
</form>
</div>
</div>
<script>
/* -- JQUERY NO TEXTAREA --
Essa parte o jquery vai pegar o número da tecla digitada
e se o número for 13(enter) ele vai enviar
*/
$('.textarea').keyup(function (e) {
if ( e.which === 13 ){ //Se a tecla for igual a 13(enter)
$('form').submit(); //Envie pra o formulário o que foi digitado
}
});
$('form').submit(function () {
var mensagem = $('.textarea').val();
$.post('manipuladores/mensagens.php?
action=enviarMensagem&mensagem='+ mensagem, function (
response
){
alert(response);
});
return false;
});
</script>
</body>
</html>
config.php
<?php
$dbhost = 'localhost';
$dbnome = 'chat';
$dbusuario = 'root';
$dbsenha = '1234';
try{
$db = new
PDO("mysql:dbhost=$dbhost;dbname=$dbnome","$dbusuario","$dbsenha");
}catch ( PDOException $e){
echo ("<label style='color:red;'> Erro: </label> ".$e->getMessage(). "
<br><p style='color:red;'>Recomenda-se buscar na internet o código do erro.
</p>");
}
?>
messages.php (inside the handlers folder)
<?php
include_once ('../config.php');
switch ( $_REQUEST['action']){
case "enviarMensagem":
//global $db;
$comandoSQL = $db->prepare('INSERT INTO mensagens SET mensagem = ?');
var_dump($comandoSQL);
$comandoSQL->execute([$_REQUEST['mensagem']]);
var_dump($comandoSQL);
break;
}
Database information name: chat; used table: messages;
Messages is made up of:
id: PK, AI
usuario: VARCHAR(45)
mensagem: TEXT
data: TIMESTAMP