Tips for converting this ajax code to long polling

I am currently using this ajax code and I was wondering if anyone knows how to change it to long polling.

Here is the code I am using:

var chat = {}
chat.fetchMessages = function () {
  $.ajax({
    url: 'ajax/ajax/chat.php',
    type: 'POST',
    data: { method: 'fetch' },
    success: function(data) {
      $('#chats').html(data);
    }
  }); 
}
chat.interval = setInterval(chat.fetchMessages, 1000);

Answer №1

To ensure continuity, the next call of fetchMessage must be placed within the callback function of the previous call:

var chat = {}
chat.fetchMessages = function () {
  $.ajax({
    url: 'ajax/ajax/chat.php',
    type: 'POST',
    data: { method: 'fetch' },
    success: function(data) {
      $('#chats').html(data);
      chat.fetchMessages(); // initiating next call
    }
  }); 
}
chat.fetchMessages(); // initial call

Answer №2

It appears that the code mentioned above is functioning correctly, but there is a concern that it may lead to an excessive amount of traffic as a result of immediately calling the function. This could potentially cause an increase in memory usage by the browser due to continuous long polling. It is recommended to introduce a settimeout function to create a delay between function calls. Additionally, clearing the cache may be beneficial. Consider exploring other options such as comet or SignalR as well.

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

Tips for iterating through a list of checked values using v-for

Currently working on a feature to create a checkbox that allows only one selection. <div id="app"> <div v-for="(question, index) in questions"> <input type="checkbox" value="question.value" v-model ...

Event not tracking properly due to missing label in GA event firing

Seeking assistance with a project I'm currently engaged in. I have created an HTML5 video containing a playlist and encountering difficulties setting up multiple labels in GA to track each individual video play. While I found code online, adapting it ...

Searching for a table element and clicking it based on its text with Protractor

<tr id="item" ng-repeat="item in itemList> <td id="code" ng-repeat="column in columns">Different Text</td> </tr> I have encountered some similar issues before, but I am still struggling to find a solution. Here is what I have at ...

What is the best way to generate a fresh JSON object within a react hook function?

I am currently facing two issues. Firstly, I am having trouble figuring out how to add/update the JSON items within a hook. Secondly, React seems to be restricting me from using the name that is stored in a previous JSON file. I am open to exploring alter ...

Employ a unique filter within the controller of your AngularJs directive

Current Situation I currently have an array of users with their information and I am using ng-repeat along with a custom directive to create HTML user cards. The scope for each card is specific to the individual user. Within the user model, there is a v ...

Transfer the information from dropped files in a div to a separate page

document.getElementById('drag_drop').ondrop = function(event) { event.preventDefault(); var form_data = new FormData(); var drop_files = event.dataTransfer.files; for(var count = 0; count < drop_files.length; count++) ...

Guide to inserting an HTML file into an article's content

After downloading an extension from freefrontedit and uploading it to my server in the directory /accordeon, I successfully accessed it by pointing my browser to . However, I am now faced with the challenge of loading the index.html into my Joomla article ...

performing an ajax request to a Rails database

My objective is to retrieve rows from the database that match a specific variable, such as a URL, and return the entire matching row in JSON format. In essence, if the URL in 'table1' matches the URL under 'eventurl' in 'table2&ap ...

My current array is arr=[1,2,3,4]. I recently added an element to it using arr.push(5). Now I want to rearrange the array to be [5,4,3,2,1]. Any suggestions on how to achieve this

I currently have an array in the following format: var arr = [1,2,3,4] // Add another element to the array arr.push(5) // Now, arr = [1,2,3,4,5] I want to print my array as The elements in the array arr are: 5,1,2,3,4 When I use Arr.reverse(), it retu ...

Exploring the use of properties in JavaScript

I recently began learning Vue.js 2, but I encountered an issue when passing props to a child component. Here's the code snippet where I pass the prop: <div class="user"> <h3>{{ user.name }}</h3> <depenses :user-id="user.id"&g ...

Is JQuery the ultimate solution for creating a dynamic multi-language website?

Embarking on a new project that requires support for multiple languages. My plan is to create a jQuery/AJAX based application with all the code in jQuery, simply calling JSONs for data. What would be the most effective approach for implementing multi-lan ...

Include the array in the 'content' property of the CSS using Jquery

I need help formatting data in CSS. The code I have is as follows: if (ext){ switch (ext.toLowerCase()) { case 'doc': pos = 'doc'; break; case 'bmp': pos = 'bmp'; break; ...

Generating an array within the custom hook results in the value being re-rendered with each change in state

While working on a custom hook in react native, I ran into an issue with the combination of useEffect and useState that led to an infinite loop. To demonstrate the problem, I created a small snack: import React, { useEffect, useState, useMemo } from &apos ...

Getting the nested object property with pluck using Lodash

I have an array of objects containing character information: var characters = [ { 'name': 'barney', 'age': 36, 'salary':{'amount': 10} }, { 'name': 'fred', 'age': ...

NextRouter does not have a property called "refresh"

Here is the provided code snippet: "use client"; import { useRouter } from "next/router"; import { useState } from "react"; export default function CreatePrompt() { const [title, setTitle] = useState(""); const ...

How to eliminate space preceding a div using jQuery?

I am trying to modify the following code snippet: <div id="one">1</div> <div id="two">2</div> <div id="three">3</div> Is there a method for me to eliminate the space before div "three" in order to achieve this result: ...

Dealing with Errors in AJAX using FluentValidation with .NET Core

How can I handle errors in FluentValidation when using form post with AJAX / jQuery? Here is my JavaScript: function Create(controlId: any) { var control = $('#' + controlId); var controller = control.data('controller'); v ...

Managing Image Quality with Unsplash API

How can we ensure high quality images are embedded on the web using Unsplash API or other methods? The image displayed in the example below appears blurry and unclear compared to the original image. Original Image link: Example of embedding the image abo ...

Access an HTML file in Text Edit on a Mac directly from a web browser

Is there a way to utilize Javascript or another appropriate script to open an HTML file in Text Edit on my Mac? I have created a local web page using Text Edit that has different tabs linking to other Text Edit files within the page. I am looking for a m ...

Managing state in React for a nested object while still maintaining the data type of the

Exploring the question further from this particular query Updating State in React for Nested Objects The process of updating nested state involves breaking down the object and reconstructing it as shown below: this.setState({ someProperty: { ...this.stat ...