I want some help creating a live chat

I am building a live chat for an IT class project using html,css,php and JS. My problem is that i don’
t know how to make this chat live-time. I have built the chat window, uploaded all the chat users but when i click to send a message on the chat window it redirects me to the ‘send_message.php’ page. The message upload successfull on my database, but i can’t display it on the chat window. I will provide bellow the chat-page scripts, and php files,both for upload and send_messages. Any help would be appreciated!

(Html-page)

<!DOCTYPE html>
<html>


<?php

session_start();
include('configuration.php');
$conn=new mysqli($servername,$username,$password,$dbname);
if($conn->connect_error){
    error_log("Error:".$conn->connect_error,3,"localhost/www/chatapp/errorlogs.txt");
    die("Connection failed:".$conn->error);
}
if(!isset($_SESSION['username'])){
    header("Location:loginform.php?");
    exit();
}
$username=htmlspecialchars($_SESSION['username']);
$stmt=$conn->prepare("Select username from registers where username=?");
$stmt->bind_param("s",$username);
$stmt->execute();
$stmt->bind_result($db_username);
$stmt->fetch();

$profile_data_retrieved=false;

if($db_username){
    $profile_data=['username'=>$db_username];
    $profile_data_retrieved=true;
}else{
    error_log("Error:".$conn->connect_error,3,"localhost/www/chatapp/errorlogs.txt");
    echo"Error";
}
$stmt->close();
$conn->close();


    






?>
<head>
<title>SecretChat</title>

<link rel="stylesheet" href="wlcmpg.css"/>





</head>

<body>
<h1>SecretChat</h1>

<?php
echo'<div class="usr">'.'Welcome'." " . htmlspecialchars($profile_data['username']).'</div>';
?>


<h3>Welcome to secretchat.</h3>
<p>This web app is a test for a project on my it school to learn how to create
chat systems using signal or pgp cryptography to create safe communication platforms.</p>
<div class="chat">
<div class="chat-window" id="chat-window">
<form action="send_message.php" method="post" id="chat-form">
<div class="chat_header" id="chatuser">Chat</div>
<div class="chat_msg"></div>
<div class="chat_footer"></div>
<input type="hidden" name="receiver" id="receiver" value="receiver_username">
<textarea placeholder="type your message" name="message"></textarea>
<button onclick="sendMessage()">Send</button>
</div>
<div class="users-list">
<ul id="users-list"></ul>
</form>
</div>


</div>
<?php

include('configuration.php');

$conn = new mysqli($servername, $username, $password, $dbname);
if ($conn->connect_error) {
    error_log("Error: " . $conn->connect_error, 3, "localhost/www/chatapp/errorlogs.txt");
    die("Connection failed: " . $conn->connect_error);
}

if (!isset($_SESSION["username"])) {
    header("Location: loginform.php?");
    exit();
}

$current_user = htmlspecialchars($_SESSION["username"]);
$current_chat_user = htmlspecialchars(isset($_GET['chat_user'])) ? $_GET['chat_user'] : '';

$stmt = $conn->prepare("SELECT username FROM registers WHERE username != ? AND username != ?");
if ($stmt === false) {
    error_log("Error preparing statement: " . $conn->connect_error, 3, "localhost/www/chatapp/errorlogs.txt");
    die("Error preparing statement: " . $conn->connect_error);
}

$stmt->bind_param("ss", $current_user, $current_chat_user);
$stmt->execute();
$stmt->bind_result($user);

while ($stmt->fetch()) {
    echo '<li onclick="openChatWindow('' . htmlspecialchars($user, ENT_QUOTES, 'UTF-8') . '')">' . htmlspecialchars($user, ENT_QUOTES, 'UTF-8') . '</li>';
}

$stmt->close();
$conn->close();
?>
<script>
function openChatWindow(username) {
    console.log('Open chat with:', username);
    document.getElementById('chatuser').textContent = username;
    document.getElementById('chat-window').style.display = 'block';
    loadMessages(username); 
}
    




</script>


    
 


    
    
</body>
</html>

(send_message php script)

<?php
session_start();
include('configuration.php');
$conn=new mysqli($servername,$username,$password,$dbname);
if($conn->connect_error){
    error_log("Error:".$conn->connect_error,3,"localhost/www/chatapp/errorlogs.txt");
    die("Connection failed:".$conn->error);
}

 if (!isset($_POST['receiver']) || !isset($_POST['message'])) {
        die("Required parameters are missing.");
    }

$sender=$_SESSION['username'];
$receiver=$_POST['receiver'];
$message=$_POST['message'];

$stmt=$conn->prepare("Insert into messages(sender,receiver,message)values (?,?,?)");
$stmt->bind_param("sss",$sender,$receiver,$message);

if($stmt->execute()){
    echo"Message sent";
}else{
    error_log("Error sending the message".$conn->connect_error,3,"localhost/www/chatapp/errorlogs.txt");
    echo"Couldn't send the message";
}

$stmt->close();
$conn->close();

?>

(loadmsg_php file)

<?php
session_start();

include('configuration.php');

if (!isset($_SESSION['username'])) {
    http_response_code(403);
    exit('Unauthorized');
}

$conn = new mysqli($servername, $username, $password, $dbname);
if ($conn->connect_error) {
    error_log("Error: " . $conn->connect_error, 3, "localhost/chatapp/errorlogs.txt");
    die("Connection failed: " . $conn->connect_error);
}

$receiver = isset($_GET['receiver']) ? trim($_GET['receiver']) : '';
$sender = $_SESSION['username'];

if (empty($receiver)) {
    http_response_code(400);
    exit('Invalid request');
}

$stmt = $conn->prepare("SELECT sender, receiver, message, timestamp FROM messages WHERE (sender = ? AND receiver = ?) OR (sender = ? AND receiver = ?) ORDER BY timestamp ASC");
$stmt->bind_param("ssss", $sender, $receiver, $receiver, $sender);
$stmt->execute();
$result = $stmt->get_result();

$messages = [];
while ($row = $result->fetch_assoc()) {
    $messages[] = $row;
}
$stmt->close();
$conn->close();





?>

New contributor

user26603446 is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.

1

Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa Dịch vụ tổ chức sự kiện 5 sao Thông tin về chúng tôi Dịch vụ sinh nhật bé trai Dịch vụ sinh nhật bé gái Sự kiện trọn gói Các tiết mục giải trí Dịch vụ bổ trợ Tiệc cưới sang trọng Dịch vụ khai trương Tư vấn tổ chức sự kiện Hình ảnh sự kiện Cập nhật tin tức Liên hệ ngay Thuê chú hề chuyên nghiệp Tiệc tất niên cho công ty Trang trí tiệc cuối năm Tiệc tất niên độc đáo Sinh nhật bé Hải Đăng Sinh nhật đáng yêu bé Khánh Vân Sinh nhật sang trọng Bích Ngân Tiệc sinh nhật bé Thanh Trang Dịch vụ ông già Noel Xiếc thú vui nhộn Biểu diễn xiếc quay đĩa Dịch vụ tổ chức tiệc uy tín Khám phá dịch vụ của chúng tôi Tiệc sinh nhật cho bé trai Trang trí tiệc cho bé gái Gói sự kiện chuyên nghiệp Chương trình giải trí hấp dẫn Dịch vụ hỗ trợ sự kiện Trang trí tiệc cưới đẹp Khởi đầu thành công với khai trương Chuyên gia tư vấn sự kiện Xem ảnh các sự kiện đẹp Tin mới về sự kiện Kết nối với đội ngũ chuyên gia Chú hề vui nhộn cho tiệc sinh nhật Ý tưởng tiệc cuối năm Tất niên độc đáo Trang trí tiệc hiện đại Tổ chức sinh nhật cho Hải Đăng Sinh nhật độc quyền Khánh Vân Phong cách tiệc Bích Ngân Trang trí tiệc bé Thanh Trang Thuê dịch vụ ông già Noel chuyên nghiệp Xem xiếc khỉ đặc sắc Xiếc quay đĩa thú vị
Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa
Thiết kế website Thiết kế website Thiết kế website Cách kháng tài khoản quảng cáo Mua bán Fanpage Facebook Dịch vụ SEO Tổ chức sinh nhật