The chat message section is failing to update due to AJAX not refreshing

I recently launched a new website and am facing challenges with the chat feature. Despite using ajax to update the chat messages without refreshing the page, the other user still needs to refresh in order to see the latest message. We are both in the same chat room and I can confirm that the chat does not auto-refresh. Below is the code snippet:

<script type="text/javascript">
var scroller = function(){
  posts = document.getElementById("posts");
  posts.scrollTop = posts.scrollHeight; 
}
var menu = 3;
var checksum = function(){
  if (menu == 3){
    document.getElementById('smileys').style.display="block";
    document.bob.smileyhider.innerHTML="&minus;";
    menu=1;
  }
  else {
    document.getElementById('smileys').style.display="none";
    document.bob.smileyhider.innerHTML="+";
    menu=3;
  }
}
//Chat ajax loader
var updater = 10;
function update(){
  var xhr;
  if(updater < 200){ updater = 200 }
  if (window.XMLHttpRequest){ xhr = new XMLHttpRequest(); }
  else { xhr = new ActiveXObject('Microsoft.XMLHTTP'); }
  xhr.onreadystatechange = function(){
    if (xhr.readyState==4 && xhr.status == 200){
      document.getElementById('posts').innerHTML = xhr.responseText;
    }
  }
  setTimeout(update, (++updater)*10);
  xhr.open("GET","chatlog<?php echo date("d");?>.log",true);
  xhr.send(null);
} 
</script>

Answer №1

  1. Make sure to initiate the ajax requests by calling the update function, instead of just defining it without executing.
  2. To continuously run the updates, consider using setInterval rather than setTimeout which only runs once.
  3. Consider setting a static value like 3 seconds for the updater variable.

/

var updater = 3000;

function update(){
  var xhr;
  if(updater < 200){ updater = 200 }
  if (window.XMLHttpRequest){ xhr = new XMLHttpRequest(); }
  else { xhr = new ActiveXObject('Microsoft.XMLHTTP'); }
  xhr.onreadystatechange = function(){
    if (xhr.readyState==4 && xhr.status == 200){
      document.getElementById('posts').innerHTML = xhr.responseText;
    }
  }

  xhr.open("GET","chatlog<?php echo date("d");?>.log",true);
  xhr.send(null);
} 

setInterval(update, updater);

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Observable task queuing

Here's the scenario: In my application, the user can tap a button to trigger a task that takes 2 seconds to complete. I want to set up a queue to run these tasks one after another, in sequence. I am working with Ionic 3 and TypeScript. What would be ...

Step-by-step guide on transferring an HTML5 sqlite result set to a server using AJAX

Imagine I have a scenario where I receive a result set as shown below: db.transaction( function(transaction) { transaction.executeSql( 'SELECT col1, col2, col3 FROM table;', [],function(transaction, result){ //need to find a ...

Observe the present time in a specific nation

Is there an authorized method to obtain and showcase the current accurate GMT time instead of relying on the easily manipulable local time on a computer? I am looking for a reliable way to acquire the current time in hours/minutes, so I can make calculati ...

What could be causing the fputcsv function to not write to my CSV file?

For some reason, I've encountered an issue while attempting to write to a .csv file using PHP. The file remains blank and no data is being added. Initially, an AJAX post request is sent to addComment.php, where the intention is to append the POST data ...

What is the best way to update a div element following a successful AJAX request?

Sharing my experience as I struggled to find a raw JavaScript solution among all the jQuery answers. I have a function that posts comments to a section, and I want the section to refresh after posting. However, my code seems to be failing to work as expec ...

I'm experiencing a connection issue despite using the same call file. Why could this be happening?

Here is my situation: I have developed a WebSocket Server using Node.js within an environment primarily based on Laravel. To mimic the functionality of Laravel's .env file, I have incorporated the dotenv package. Recently, I came across a strange obs ...

What is the best way to ensure TypeScript recognizes a variable as a specific type throughout the code?

Due to compatibility issues with Internet Explorer, I find myself needing to create a custom Error that must be validated using the constructor. customError instanceof CustomError; // false customError.constructor === CustomError; // true But how can I m ...

Add new data to an existing array in Angular 7 without overwriting it

After clicking a button, I'm retrieving data from the WordPress API: <a (click)="initGetComments()">Get comments</a> This is the code snippet: export class AppComponent { commentsResults: CommentsItem[] = []; ...

Issue with Internet Explorer: Refusing to run javascript included in AJAX-loaded content

While loading AJAX content that includes a javascript function using the jQuery .load function with done() on completion, I am facing an issue. $('#content').load(a, done); function done() { if(pagejs() == 'function') { ...

Guide on how to use Vue's watch feature to monitor a particular property within an array

I am interested in observing the "clientFilter" within an array TableProduit: [ { nr_commande: 0, date_creation: "", id_delegue: "1", clientFilter: "" } ], ...

Looking to show a div upon clicking a link with the use of Javascript

Looking for a workaround due to restrictions on using alert or any Js dialog box, I need to create some sort of magic trick: 1. Create a div with a link named "info". 2. Develop an invisible div that will serve as my "PopUp" containing random information. ...

php Ajax call functions correctly on local machine, but fails on server

While attempting to implement a progress bar during script execution, I encountered an issue. The progress bar works correctly in Visual Studio testing, but fails when deployed on a server. Is there a PHP or IIS configuration that might be hindering its fu ...

What is causing my function to not wait for the resolution of the Promise?

checkout.ts updateGlobalValue(){ updateShadowDomButton(); let globalValue = fetchGlobalValue() } web_component_render.ts let globalValue; async fetchData() { let booleanFromApi = await callToExternalAPI(); return booleanFromApi; } functi ...

The values in my JavaScript don't correspond to the values in my CSS

Is it possible to retrieve the display value (display:none; or display:block;) of a div with the ID "navmenu" using JavaScript? I have encountered an issue where I can successfully read the style values when they are set within the same HTML file, but not ...

Error: Unable to assign a value to the statusCode property because it

During the development of my application backend, I encountered an error while working on the user login route. When testing the route using Postman, I received the following error message: UnhandledPromiseRejectionWarning: TypeError: Cannot set propert ...

Is there a way to integrate a snap carousel in a vertical orientation?

I am looking to make a List utilizing the snap carousel component, but I'm having trouble getting it set up. Can anyone help me with this? ...

Iron-Ajax is showing [Object object] on the screen

My current setup includes a database named test and a table called users. Within the users table, there are columns id, name, and contact. I am using iron-ajax to retrieve the name from the database table and showcase it. Simply using {{ajaxResponse}} res ...

Track your status with jQuery technology

I have a link: <a href="/test/number/3/phone/0">33df</a> Is there a way to determine if the words 'number' and 'phone' are present in this link? I am looking for a function similar to: check('number', ' ...

No location matched any routes

I'm currently working on a notes application, and I've encountered an error when trying to edit the notes. The error message says "No routes matched location id ...". Any idea what could be causing this issue? The approach I'm taking is to ...

Exploring the method to search across various fields in Vue.js 2

In my Vue.js 2 application, I am attempting to search or filter through three fields: firstname, lastname, and email. Unlike Vue 1, Vue 2 does not include a built-in filter method. As a result, I have created a custom method that can only filter through on ...