Home > Software design >  How to refresh page every 2 seconds?
How to refresh page every 2 seconds?

Time:01-18

I wanna to setup a web messenger. So I want to reload my page every 1 or 2 seconds. Actually I want a silent reload to get new chats from my database. Most methods just reload page and clear all inputs. Please help me.

I tried: function loadlink(){ $('#links').load('test.php',function () { $(this).unwrap(); }); } loadlink(); setInterval(function(){ loadlink() }, 5000);

And: <meta http-equiv="refresh" content="2">

CodePudding user response:

Refreshing your whole page every 2 seconds is not an excellent idea. You should read more on WebSockets or use ajax

CodePudding user response:

This tag refreshes the whole page, not ideal:

meta http-equiv="refresh" content="2"

Here I found a complete article about this.

It uses php, MySql (to store chat and authentication) and vanilla js ajax calls to refresh chat.

As others stated executing ajax requests every 2 seconds might slow down your server. Better to try with 3-5 secs.

This example uses 5 seconds. It is set by setInterval(), using milliseconds. 5000ms = 5 sec.

Here is the ajax part that updates conversations (copied from the example):

setInterval(() => {
    // If the current tab is 2
    if (currentChatTab == 2) {
        // Use AJAX to update the conversations list
        fetch('conversations.php', { cache: 'no-store' }).then(response => response.text()).then(html => {
            let doc = (new DOMParser()).parseFromString(html, 'text/html');
            document.querySelector('.chat-widget-conversations').innerHTML = doc.querySelector('.chat-widget-conversations').innerHTML;
            conversationHandler();
        }); 
    // If the current tab is 3 and the conversation ID variable is not NUll               
    } else if (currentChatTab == 3 && conversationId != null) {
        // Use AJAX to update the conversation
        fetch('conversation.php?id='   conversationId, { cache: 'no-store' }).then(response => response.text()).then(html => {
            // The following variable will prevent the messages container from automatically scrolling to the bottom if the user previously scrolled up in the chat list
            let canScroll = true;
            if (document.querySelector('.chat-widget-messages').lastElementChild && document.querySelector('.chat-widget-messages').scrollHeight - document.querySelector('.chat-widget-messages').scrollTop != document.querySelector('.chat-widget-messages').clientHeight) {
                canScroll = false;
            }                    
            let doc = (new DOMParser()).parseFromString(html, 'text/html');
            // Update content
            document.querySelector('.chat-widget-messages').innerHTML = doc.querySelector('.chat-widget-messages').innerHTML;
            if (canScroll && document.querySelector('.chat-widget-messages').lastElementChild) {
                // Scroll to the bottom of the container
                document.querySelector('.chat-widget-messages').scrollTop = document.querySelector('.chat-widget-messages').lastElementChild.offsetTop;
            }                   
        });  
    // If the current tab is 3 and the status is Waiting           
    } else if (currentChatTab == 3 && status == 'Waiting') {
        // Attempt to find a new conversation between the user and operator (or vice-versa)
        fetch('find_conversation.php', { cache: 'no-store' }).then(response => response.text()).then(data => {
            if (data != 'error') {
                // Success! Two users are now connected! Retrieve the new conversation
                getConversation(data);
            }
        });               
    }
}, 5000); // 5 seconds (5000ms) - the lower the number, the more demanding it is on your server.

Note: it has many more parts as well, the ajax call is only a small slice of the cake.

  • Related