You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

基于Codeigniter与Ajax实现Openfire聊天记录页面数据更新

Real-Time Chat Updates with Codeigniter, Ajax & Openfire

Great question! Let's break down how to implement real-time chat updates using your existing Codeigniter setup. The key changes will be adjusting your controller to return JSON data (instead of loading a view) and adding front-end Ajax logic to periodically fetch new messages.

Step 1: Modify Your Codeigniter Controller Method

First, update your get_chats method to return JSON instead of rendering a view. We'll also add support for fetching only new messages since the last update (using the messageID from Openfire's ofMessageArchive table) to avoid reloading all messages every time.

public function get_chats() {
    // Get the last message ID from the request (sanitized to prevent SQL injection)
    $last_id = $this->input->get('last_id', true) ?: 0;
    
    $this->db->select('*');
    $this->db->from('ofMessageArchive');
    // Only fetch messages newer than the last one we loaded
    $this->db->where('messageID >', $last_id);
    // Order by timestamp to maintain conversation order
    $this->db->order_by('sentDate', 'ASC');
    
    $query = $this->db->get();
    $messages = $query->result();
    
    // Calculate the newest message ID to use in the next request
    $new_last_id = !empty($messages) ? end($messages)->messageID : $last_id;
    
    // Return data as JSON
    header('Content-Type: application/json');
    echo json_encode([
        'messages' => $messages,
        'last_id' => $new_last_id
    ]);
    exit; // Ensure no additional output is sent
}

Step 2: Front-End HTML Structure

Create a container where your chat messages will be displayed. This can be a <div> or <table>—we'll use a div for simplicity:

<div id="chat-container" style="height: 400px; overflow-y: auto; border: 1px solid #ccc; padding: 10px;">
    <!-- Messages will be appended here dynamically -->
</div>

Step 3: Ajax Implementation for Real-Time Updates

Use jQuery (or vanilla JS) to periodically fetch new messages and update the chat container. We'll track the last message ID to only load new content each time:

$(document).ready(function() {
    let lastMessageId = 0;
    const chatContainer = $('#chat-container');
    
    // Function to fetch and display new messages
    function loadNewMessages() {
        $.ajax({
            url: '/your-controller-name/get_chats', // Replace with your actual controller URL
            method: 'GET',
            data: { last_id: lastMessageId },
            dataType: 'json',
            success: function(response) {
                if (response.messages.length > 0) {
                    // Update the last message ID for future requests
                    lastMessageId = response.last_id;
                    
                    // Loop through new messages and append them to the container
                    $.each(response.messages, function(index, msg) {
                        // Create a safe, sanitized message element (prevents XSS)
                        const messageElement = $('<div class="chat-message" style="margin-bottom: 10px; padding: 5px; background: #f5f5f5;"></div>');
                        messageElement.append($('<strong></strong>').text(msg.senderJID));
                        messageElement.append($('<p></p>').text(msg.body));
                        messageElement.append($('<small></small>').text(new Date(msg.sentDate).toLocaleString()));
                        
                        chatContainer.append(messageElement);
                    });
                    
                    // Auto-scroll to the bottom to show the latest messages
                    chatContainer.scrollTop(chatContainer[0].scrollHeight);
                }
            },
            error: function(xhr, status, error) {
                console.log('Error fetching messages:', error);
            }
        });
    }
    
    // Load messages immediately when the page loads
    loadNewMessages();
    
    // Check for new messages every 2 seconds (adjust based on your needs)
    setInterval(loadNewMessages, 2000);
});

Key Notes

  • URL Replacement: Make sure to replace /your-controller-name/get_chats with the actual URL path to your controller method.
  • XSS Protection: Using jQuery's .text() method instead of raw HTML insertion prevents cross-site scripting attacks if messages contain user-generated content.
  • Interval Adjustment: The 2-second interval (2000ms) is a balance between real-time updates and server load. You can decrease it for more frequent updates or increase it to reduce traffic.
  • WebSockets Alternative: For truly instant updates, consider using WebSockets (e.g., with Ratchet for PHP) instead of polling. However, polling is simpler to implement with your current stack.

内容的提问来源于stack exchange,提问作者Rajan

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.25 03:33:55