Is there a way to update AJAX requests every (n) seconds using pure JavaScript, without relying on jQuery?

Looking to set up a JavaScript function that will periodically poll the server every (n) seconds. What's the best way to achieve this using JavaScript?

Answer №1

If you are utilizing jQuery library:

var timeDelay = 5;

setInterval(function(){
    $.ajax({
        url: 'something.something',
        data: 'something'
    });
}, timeDelay * 1000)

If not using jQuery:

var timeDelay = 5;

setInterval(function(){
    some_ajax_function();
}, timeDelay * 1000)

Another approach as proposed by @Felix:

var timeDelay = 5;
some_ajax_function(timeDelay);

function some_ajax_function(timeDelay){
     ..ajax
     onsuccess: setTimeout(function(){some_ajax_function(timeDelay);}, 
                      timeDelay * 1000)
}

Answer №2

Here's an easy way to achieve this:

window.setInterval("performAjaxRequestFunction", time_in_ms);});

Hope you find this helpful :)

Answer №3

To start, our first step is to create the ajax request object, taking into consideration different browsers.

var xmlhttp;
if (window.XMLHttpRequest)
  {
  // code for IE7+, Firefox, Chrome, Opera, Safari
  xmlhttp=new XMLHttpRequest();
}
else
  {
   // code for IE6, IE5
   xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}

Next, we will define a function to send the request.

function askData(){
   xmlhttp.open("GET","myinfosource.php",true);  
   xmlhttp.send(); 
}

Subsequently, we will create an event handler that modifies the HTML content upon receiving the information back.

xmlhttp.onreadystatechange=function()
  {
  if (xmlhttp.readyState==4 && xmlhttp.status==200) 
    {
    document.getElementById("myDiv").innerHTML=xmlhttp.responseText;
  }

}

Finally, we introduce a setInterval function on the initial function to execute it at regular intervals.

setInterval('askData',10000);

This setup ensures your data remains up-to-date.

The above process highlights the importance of using frameworks like jQuery for AJAX operations as they streamline browser compatibility issues, allowing developers to focus on their tasks effortlessly.

Answer №4

I have implemented a web.xml configuration where a servlet with the URL Pattern /UpdateCount is responsible for delivering dynamic data/content to a specific countStatDiv div element on the JSP page.

To ensure that the content within the countStatDiv is refreshed every 30 seconds, the following JavaScript code utilizes a GET method. The interval of 30 seconds can easily be adjusted as needed:

                <script>
                    var request;
                    var seconds=30;
                    function getRequestObject(){
                    setInterval(function() {sendRequest();},seconds*1000);
                    if (window.ActiveXObject){
                    return (new ActiveXObject("Microsoft.XMLHTTP"));
                    } else if (window.XMLHttpRequest){
                    return(new XMLHttpRequest());
                    } else {
                    return (null);
                    }
                    }
                    function sendRequest(){
                    request = getRequestObject();
                    request.onreadystatechange = handleResponse;
                    request.open("GET", "../UpdateCount", true);
                    request.send(null);
                    }
                    function handleResponse(){
                    if((request.readyState == 4)&amp;&amp;(request.status == 200)){
                    var serverResponse = request.responseText;
                    var statCtrl=document.getElementById("countStatDiv");
                    statCtrl.innerHTML=serverResponse;
                    }
                    }
                </script>

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

The addition of one hour to the date time format increases the total time

Currently, I am retrieving a datetime column value from a database table as 2015-03-04 21:00:00 UTC. When attempting to convert this format into a datetime picker, the following code is used: date = moment($("#event_start").val()); // date time value fro ...

Loop through ng-options using ng-repeat that are linked to the same ng-model

This situation may seem odd, but I am willing to adjust the API Data if necessary. My requirement is to have multiple dropdowns sharing the same ng-model. The Question: Why does ng-model become unique when using the same variable name? How can I ensu ...

Utilize React-Charts.js-2 with ChartJS to create a customized bar chart

When creating bar graphs based on monthly data, everything works fine expect for the fact that the order of the months is not maintained and it appears mixed up in each rendering. The API provides the following data: { { "_id": 2022, &qu ...

Customize the CSS for MaterialUI's TablePagination's MenuItem

Having trouble figuring out how to override CSS for the child component MenuItem within TablePagination? Check out this link for more information: https://github.com/mui-org/material-ui/blob/master/packages/material-ui/src/TablePagination/TablePagination.j ...

Retrieving Session Data in Javascript

How can I access the value of $_SESSION['total'] in JavaScript to use it within a function? What I have tried: var total = '<%= Session["total"]%>'; Output: <%= Session["total"]%> var total = <?php $_SESSION['tota ...

"Efficiently transferring a large file using AJAX and sending it via POST to a

I am facing a challenge with a small script that I am developing. The script is designed to download relatively large files (around 15Mb each) from one domain using AJAX, and then upload/post them to another domain also through AJAX. Downloading the files ...

Avoid refreshing the page while submitting the data in the form

Trying to submit form data without page refresh and display a jQuery dialog upon completion. This is the original code: <script> $( function() { $('#dialog-message').dialog({ autoOpen: false, title: 'Basic Dialog&a ...

Troubles with Uploading Images and Validating Forms in Next.js 14 using Shadcn, Zod, and React Hook Form

I'm currently experiencing challenges with image upload and form validation in my Next.js 14 application using Shadcn, Zod, and React Hook Form. Specifically, I have a user profile creation form where I encounter the following issues: Image Upload Pr ...

Struggling with a straightforward issue in Ajax that is proving to be a challenge to resolve

I've written a simple code to call an asmx webservice (xml). function maxTransaccion() { $.ajax({ type: "POST", url: "WebService.asmx/MAxTransaccion", contentType: "application/json; charset=utf-8", dataType: "json ...

Retrieving the CSS property values for a specific element using Selenium

Imagine a scenario where I locate an element by its XPath using: WebElement element = driver.findElement(By.xpath("specific XPath")); While I can retrieve the value of a single CSS property with element.getCssValue("specific property"), is there a way to ...

Troubleshooting: Issue with UpdatePanel or RadAjaxPanel functionality in RadGrid's EditForm template

I'm currently working with a RadGrid that has an EditForm FormTemplate integrated. Within this form, there is a RadComboBox list of companies. The goal is to have another RadComboBox populated with a list of locations when a user selects a company. I ...

Tips for managing erroneous data in csv files using Node.js

I am currently working on an application that parses csv files using the csv module. It is functioning well, but I am facing a problem where if there is a bad row in the csv file, the entire process fails. Is there a way to skip bad rows and continue stre ...

The Challenge of Dynamic Angular Components

Upon triggering the blur event of the contenteditable div, I observe changes and dynamically generate new strings with additional spans to update the same div accordingly. However, a challenge arises when all text is deleted from the contenteditable div, r ...

Choosing a random element in React: A step-by-step guide

I'm currently working on a dynamic website that aims to load a random header component upon each refresh. Despite my various attempts, the functionality operates smoothly during the initial load but consistently throws this error on subsequent refresh ...

Is there a way to input row value directly into my modal?

Is there a way to retrieve the data from the table row where my buttons are located? I attempted using {{row.name}} as a value in my modal, but it doesn't seem to be working. What is the correct method to achieve this? Below is the HTML code for the ...

Can you identify the mistake in the XML response?

I encountered an issue with my PHP code (getRout.php) which is meant to respond in XML format. The error message I received was: XML Parsing Error: no element found Location: http://127.0.0.1/direction2/getRout.php Line Number 1, Column 1: edit To view ...

Modify the font style of numbers based on the keyboard language selected by the user

Is it possible to change the font family of numbers in input fields based on the user's keyboard language? For example, if the user is typing in Persian, the numbers should be displayed in a Persian font, and when they switch to an English keyboard, t ...

What is the best way to handle the return value from using indexOf on a string?

I am looking to manipulate the value returned by a specific conditional statement. {{#each maindata-hold.[2].qa}} <div class="section"> <a href="javascript:void(0)" class="person-link" id="{{id}}"> <span class="name- ...

Performing a Javascript query to update the value in a spreadsheet with Selenium integration

How can I set a cell value using JavaScript in Selenium when the element has been created using spreadjs and I am unable to access the element's value? string query = "GcSpread.Sheets.findControl(document.getElementById(\"" + _sheetName + "&bsol ...

Dynamic adjustment of div size to fit the screen when resizing, based on the svg proportions

Is it possible to use CSS and HTML to automatically adjust the colored divs around the black SVG to fill in any extra width or height of the pink space when the screen size is resized? There is a pink div behind the logo that serves as an example of the sp ...