Integrating API Requests for Dynamic Chat Interaction in Symfony

Integrating API Requests for Dynamic Chat Interaction

Welcome back! In the previous lesson, you set up a basic chat interface using Symfony and Twig. This laid the foundation for creating a user-friendly web application. Now, we will take the next step by connecting this interface to our backend API. This connection is crucial for transforming our static interface into a dynamic, interactive chat application. By the end of this lesson, you will understand how to integrate the frontend with the backend, enabling real-time communication between the user and the server.

Connecting Twig Templates with API Endpoints

Now that we have our API endpoints set up in Symfony, we need to connect our Twig template to these endpoints. This connection allows our chat interface to communicate with the server, sending user messages and receiving responses.

Initializing Chat Variables in Twig Templates

To maintain the current user and chat state in the browser, we store both values in JavaScript variables:

{# templates/chat/chat.html.twig #}
<script>
    // Initialize variables to store the current user and chat IDs
    let currentUserId = null;
    let currentChatId = null;
</script>

These variables are populated from the API when a new chat is created. The frontend uses them when sending messages so the backend can continue the same conversation.

Understanding the Chat Template Structure

Let's examine the basic HTML structure of our chat interface:

{# templates/chat/chat.html.twig #}
<!DOCTYPE html>
<html>
<head>
    <title>Customer Service Chat</title>
</head>
<body>
    <div class="header">
        <h1>Welcome to Our Customer Service</h1>
        <p>How can we help you today?</p>
    </div>
    <div id="chat-container">
        <div id="messages"></div>
        <div class="input-container">
            <div class="input-wrapper">
                <input type="text" id="message-input" placeholder="Type your message...">
            </div>
            <button onclick="sendMessage()">Send</button>
            <button id="new-chat-btn" onclick="startNewChat()">New Chat</button>
        </div>
    </div>

    <script>
        // JavaScript code will go here
    </script>
</body>
</html>

This HTML structure creates a simple chat interface with a header, message display area, and input controls. The interface includes a text input for messages, a send button, and a button to start a new chat, providing all the necessary elements for user interaction.

The JavaScript initialization and core functions handle the chat functionality:

<script>
    // Get references to the messages container and message input field
    const messagesContainer = document.getElementById('messages');
    const messageInput = document.getElementById('message-input');

    // Initialize variables to store the current user and chat IDs
    let currentUserId = null;
    let currentChatId = null;

    // Start a chat automatically when the page loads
    document.addEventListener('DOMContentLoaded', startNewChat);
    
    function appendMessage(role, content) {
        // Create a new div element for the message
        const messageDiv = document.createElement('div');
        
        // Assign a class to the message based on its role (user or assistant)
        messageDiv.className = `message ${role}`;
        
        // Set the text content of the message
        messageDiv.textContent = content;
        
        // Append the message to the messages container
        messagesContainer.appendChild(messageDiv);
        
        // Scroll the messages container to the bottom to show the latest message
        messagesContainer.scrollTop = messagesContainer.scrollHeight;
    }
</script>

This JavaScript code initializes our chat interface by getting references to key DOM elements and setting up event listeners. The appendMessage function is a utility that adds new messages to the chat display, differentiating between user and assistant messages with CSS classes, and ensures the chat always scrolls to show the most recent messages.

Sign up

Join the 1M+ learners on CodeSignal

Be a part of our community of 1M+ users who develop and demonstrate their skills on CodeSignal