i'm creating a webchat app and i have a problem - i want to send a post with message from user and add it to database, but i don't want to reload my page, i've done something like that, but it is not working:
file index.php:
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script>
setInterval(function () {
$("#chat-content").load('chat.php');
},10);
$("#submit").click(function(){
var clientmsg = $("#message").val();
$.post("chat.php", {text: clientmsg});
$("#message").attr("value", "");
return false;
});
</script>
</head>
<body>
<div id="chat-content">
</div>
</body>
<form method="post" id="messageform">
<input type="text" id="message" name="message"></input>
<input id="submit" name="sumbit" type="submit" value="Send" />
</form>
File chat.php:
<?php include('db.php');
$query = "SELECT * FROM `czat`;";
$result = $con->prepare($query);
$result->execute();
$count = $result->fetchColumn();
if($count > 100){
$query = "TRUNCATE `czat`;";
$result = $con->prepare($query);
$result->execute();
}
$query = "SELECT * FROM `czat` ORDER BY id ASC LIMIT 10;";
$result = $con->prepare($query);
$result->execute();
while($row = $result->fetch()){
echo $row["nazwa"].' - '.$row["tresc"].'<br>';
}
if(isset($_POST['text'])){
$text = $_POST['text'];
$query = "INSERT INTO `czat` (`id`, `nazwa`, `tresc`) VALUES (NULL, 'dd', '$text');";
$result = $con->prepare($query);
$result->execute();
}
?>
db.php is a standard connection to db.