Chat Application

Aug 11, 2024

Presentation

The application allows users to send and receive messages in real-time. It is hosted on chatr410.alwaysdata.net and the source code is available on GitHub.

Project Structure

The repository contains the following folders and files:

  • api/: Contains PHP scripts to handle server-side requests.
  • php/: Include PHP files for business logic.
  • script/: Contains JavaScript files for client-side functionalities.
  • static/: Used for static resources such as images.
  • style/: Contains CSS files for styling the application.
  • index.html: The main entry point of the application.

Key Features

Real-Time Communication

The application uses AJAX requests or WebSocket technology to enable real-time communication between users.

Message Management

Messages are stored in a database, with PHP scripts used to retrieve and insert messages.

User Interface

The interface is built with HTML and styled using CSS. Dynamic interactions are managed by JavaScript.

Hosting

The application is hosted on AlwaysData.

API Endpoints

Fetch Messages Endpoint

<?php
require_once '../../php/recuperer.php';

header("Access-Control-Allow-Origin: *");
header("Access-Control-Allow-Methods: GET");
header('Content-Type: text/html');

switch($_SERVER['REQUEST_METHOD']){
    case "GET":
        $messages = getMessages();
        echo formatMessagesAsHTML($messages);
        break;
    default:
        http_response_code(405);
        echo json_encode(['error' => 'Method Not Allowed']);
        break;
}
?>

Send Message Endpoint

<?php
require_once '../../php/enregistrer.php';

header("Access-Control-Allow-Origin: *");
header("Access-Control-Allow-Methods: POST");
header("Access-Control-Allow-Headers: Content-Type, Authorization");

switch($_SERVER['REQUEST_METHOD']){
    case "POST":
        $postedData = file_get_contents('php://input');
        $data = json_decode($postedData, true);
        if (isset($data["pseudo"]) && isset($data['message'])){
            if(setMessage($data["pseudo"], $data["message"], time())){
                deliverResponse(200, 'Sucessfull');
            }else{
                deliverResponse(500, "Internal Error");
            }
        }else{
            deliverResponse(400,"Le pseudo et le message n'est pas spécifié");
        }
}
?>

Client-Side Interaction

JavaScript for Real-Time Updates and Sending Messages

import getXHR from './utils.js';

const pseudo = document.getElementById('pseudo');
const message = document.getElementById('message');
const button = document.getElementById('button-send');
let pseudoValue = "";
let messageValue = "";
pseudo.addEventListener('input', (event) => {
    pseudoValue = event.target.value;
});
message.addEventListener('input', (event) => {
    messageValue = event.target.value;
});
button.addEventListener('click', envoyer);

document.addEventListener('DOMContentLoaded', (event) => {
    setInterval(fetchMessages, 2000);
});

function fetchMessages(){
    const messagesContainer = $("#messages-container");
    if (messagesContainer.length) {
        messagesContainer.load('/api/recupererMessage/endpoint.php', function(response, status, xhr) {
            if (status == "error") {
                console.log("Erreur: " + xhr.status + " " + xhr.statusText);
            } else {
                console.log("Messages récupérés");
            }
        });
    } else {
        console.error("Element with ID 'messages-container' not found.");
    }
}

async function envoyer(){
    let toSend = {"pseudo":pseudoValue,"message":messageValue};
    getXHR('/api/envoyerMessage/endpoint.php',"POST",JSON.stringify(toSend))
    .then(data => JSON.parse(data))
    .then(data => console.log(data))
    .then(() => message.value = "")
    .catch(err => console.error(err));
}

function handleKeyDown(event) {
    if (event.key === 'Enter') {
        envoyer();
        const button = document.querySelector('button');
        button.classList.add('scale-120', '-rotate-90');
        setTimeout(() => {
            button.classList.remove('scale-120', '-rotate-90');
        }, 300);
    }
}

You can have a look to other projects here.

Made with 🫶

paquies