I am trying to create a rudimentary chat app using PHP and I would like the page to update every 5 or so seconds with new messages that once sent get stored in a Mysql Database. This is my "webmessenger.php":
<html>
<head>
<script type="http://code.jquery.com/jquery-2.1.0.min.js"></script>
</head>
<style>
#content{
margin-bottom: 20px;
padding: 20px;
background-color: white;
box-shadow: 0 4px 8px 0 rgba(0, 0, 0, 0.2), 0 6px 20px 0 rgba(0, 0, 0, 0.19);
#container{
margin: 0 auto;
}
}
</style>
<body>
<div id = "container">
</div>
<form action="webmessenger.php" method="post">
<input type="text" name = "message"/>
<input type = "submit" value = "send"/>
</form>
</body>
<script language="javascript" type="text/javascript">
function loadlink(){
$('#container').load('update.php',function () {
$(this).unwrap();
});
}
loadlink(); // This will run on page load
setInterval(function(){
loadlink() // this will run after every 5 seconds
}, 5000);
</script>
<?php
include("update.php");
$mysqli = new mysqli("SERVER IP", "USER", "PASS", "DB NAME");
if ($mysqli->connect_errno) {
echo "Failed to connect to MySQL: (" . $mysqli->connect_errno . ") " . $mysqli->connect_error;
}
if ($_SERVER['REQUEST_METHOD'] == 'POST'){
$message = $_POST['message'];
$sql = "INSERT INTO `messages` (text) VALUES ('$message')";
$mysqli->query($sql);
}
?>
</html>
this code successfully prints out the search bar, and the last known entries into the DB since I included update.php which contacts the DB and prints each row which contains a message. However, the periodic refresh with ajax is not happening because when you open two windows and send a message on one window, it never pops up on the other.
This is update.php for reference:
<?php
$mysqli = new mysqli("DB IP", "USER", "PASS", "DB NAME");
if ($mysqli->connect_errno) {
echo "Failed to connect to MySQL: (" . $mysqli->connect_errno . ") " . $mysqli->connect_error;
}
$sql = "SELECT * FROM `messages`";
$res = $mysqli->query($sql);
if($res->num_rows > 0){
while($row = $res->fetch_assoc()){
$rownum=$row["id"];
echo $row["text"]."<br />";
}
}
else
{
echo "No Record Found!";
}
?>
If anyone could help me out and let me know why the function is not working the way it should, that'd be much appreciated. Thanks in advance.
</div>