Is it possible to execute an ajax function at regular intervals until a specific condition is fulfilled?

My application consists of two JSP pages. One is responsible for the UI, while the other processes the response.

UICounter.jsp:

<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Page</title>
<script>
function createRequest() {
      var xmlHttpReq = false;
      
      if (window.XMLHttpRequest) {
        xmlHttpReq = new XMLHttpRequest();
      } else if (window.ActiveXObject) {
        try {
          xmlHttpReq = new ActiveXObject("Msxml2.XMLHTTP");
        } catch (exp1) {
          try {
            xmlHttpReq = new ActiveXObject("Microsoft.XMLHTTP");
          } catch (exp2) {
            xmlHttpReq = false;
          }
        }
      }
      return xmlHttpReq;
    }

function submitRequest() {
      var xmlHttpRequest = createRequest();
      xmlHttpRequest.onreadystatechange = handleReadyState(xmlHttpRequest);
      xmlHttpRequest.open("POST", "Control.jsp", true);
      xmlHttpRequest.setRequestHeader("Content-Type",
          "application/x-www-form-urlencoded");
      xmlHttpRequest.send(null);
    }

function handleReadyState(xmlHttpRequest) {
      return function() {
        if (xmlHttpRequest.readyState == 4) {
          if (xmlHttpRequest.status == 200) {
              var count = parseInt(xmlHttpRequest.responseText);
              document.getElementById("counterLabel").innerHTML = count;

          } else {
            alert("HTTP error " + xmlHttpRequest.status + ": " + xmlHttpRequest.statusText);
          }
        }
      };
    }

</script>   
</head>
<body>
<div id="counterLabel">0 </div>
<script type="text/javascript">submitRequest();</script>  
</body>
</html>

Control.jsp:

<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>
<%
if(session.getAttribute("counter") != null && !session.getAttribute("counter").toString().equals(""))
{
    String stringStatus = session.getAttribute("counter").toString().trim();
    int statusCounter = Integer.parseInt(stringStatus);
    session.setAttribute("counter",String.valueOf(++statusCounter));

}else{
    session.setAttribute("counter",String.valueOf(1));
    out.print(session.getAttribute("counter"));
}
%>
</body>
</html>

I am looking to implement a feature where AJAX calls are made until a certain condition is met. I have attempted to call the same function (submitRequest()) recursively within the AJAX response loop until the result reaches 100. However, this approach does not seem to be functioning correctly. Could someone provide guidance on how to achieve this goal? Any examples or additional clarification would be highly appreciated. Thank you!

Answer №1

Utilize jQuery and consider implementing something along these lines:

function sendRequest() {
    $.ajax({
        type: "POST",
        url: "Control.jsp",
        success: function (data) {
            if(<your condition>) {
                setTimeout(sendRequest, 100);
            } 
        },
        error: function () {
            // Handle errors
        }
    });
}

Answer №2

Utilize the setInterval method.

function fetchData(){
    $.ajax({
        url:"/xxx/xxx",
        method: "GET",
        dataType: "json",
        success: function (data) {
            //---
        }
    });
}

 /**fetch data periodically */
 fetchData();
 var intervalTimer = setInterval(function(){
     console.log("ping..");
     fetchData();
 },10000);



 /** stop after 3 minutes if necessary*/
 setTimeout(function(){
    //stop the interval timer
    window.clearTimeout(intervalTimer);
 },180000);

The use of the intervalTimer object will allow for stopping the loop at a later time.

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

Photos failing to load in the image slider

Although it may seem intimidating, a large portion of the code is repetitive. Experiment by clicking on the red buttons. <body> <ul id="carousel" class="carousel"> <button id="moveSlideLeft" class="moveSlide moveSlideLeft"></button& ...

What is the best way to use AJAX to load a PHP file as a part

I'm exploring different methods for making an AJAX call with an included file. Let's create a simple working example. Initially, I have my main index.php file which contains the following content. In this file, I aim to access all the data retur ...

How can I edit this code in JSPDF to print two pages instead of just one?

Currently, I have a script that can generate a PDF from one DIV, but now I need to create a two-page PDF from two separate DIVs. How can I modify the existing code to achieve this? The first DIV is identified as #pdf-one and the second DIV is #pdf-two. p ...

leaving code block using Express and Node

My code is displayed below: // Implement the following operations on routes ending with "users" router.route('/users') .post(function(req, res, next) { var user = new User(); user.username = req.body.username; user.p ...

What is the procedure for adding a URL path in jQuery?

When using $(this).attr("href"); in the jQuery Ajax url field, it correctly retrieves the URL path. However, if I try to use a prefix in front of it like this: $.ajax({ type: 'GET' url: 'api/' + $(this).attr("href"); }) the co ...

The handleChange function fails to trigger when selecting a date using Material UI components

I am currently facing an issue with the material ui datepicker. When I click on a date, the selected date is not chosen and the date window does not close. I suspect this is due to passing the date into another file and the handleChange function (from Form ...

"Encountering difficulties while setting up an Angular project

I am currently working on setting up an Angular project from scratch. Here are the steps I have taken so far: First, I installed Node.js Then, I proceeded to install Angular CLI using the command: npm install -g @angular/cli@latest The versions of the ...

Guide on Generating SAS Token for Azure Table Storage in a jQuery Application

I am currently working on a jQuery web application that requires read-only access to an Azure Table Storage, fetching one record at a time by passing in the PartitionKey and RowKey. To simplify my code, I have integrated the Azure Storage JavaScript Client ...

Implement Material UI TextField to ensure all required fields are properly formatted

Looking to customize the underline border color of TextFields marked as mandatory within a form using react-hooks-form. I understand that I need to define a style for these fields, but I'm struggling with where to start... This is the current code s ...

What could be causing the recurring appearance of the success alert message in an AJAX call to a PHP script in this particular situation?

Below you will find two code blocks, each designed to handle an AJAX call to a PHP file upon clicking on a specific hyperlink: <script language="javascript" type="text/javascript"> $(".fixed").click(function(e) { var action_url1 = $(th ...

If you don't get the correct response from the $.ajax success function

I am utilizing the $.ajax function to retrieve content, however I am encountering an issue when attempting to display special tags from it. The data appears to be missing! This is how I am currently handling it: $(document).ready(function(){ $("button") ...

Tips for passing multiple values with the same key in Axios as parameters

I need to develop a function that allows users to select multiple categories and subcategories, then send their corresponding ids as a query string using Axios. For example, if a user selects category IDs 1 and 2, along with subcategory IDs 31 and 65, the ...

Is there a way to swap out multiple characters within a string when using ng-repeat in AngularJS?

How can I replace multiple characters in a string using ng-repeat in AngularJS? I've tried the following code, but it's not working. I need to remove #, _, and . from the strings in my list. How can I achieve this in AngularJS? <body> &l ...

Can we access local storage within the middleware of an SSR Nuxt application?

My Nuxt app includes this middleware function: middleware(context) { const token = context.route.query.token; if (!token) { const result = await context.$api.campaignNewShare.createNewShare(); context.redirect({'name': &a ...

Modify the content in the v-navigation-drawer upon clicking

I am currently working on a project with a v-navigation-drawer and two buttons. The first button is designed to open the drawer, while the second one should change the content of the drawer without closing it. I want the content to update instantly without ...

Turn off the ability to click on images, but allow users to access the right

https://i.stack.imgur.com/jriaP.png Example image sourced from reddit.com Illustration represents the desired effect using CSS and possibly JS. In essence: I aim to make an image on a website unclickable to its imageURL There should be a context menu ...

Tips for formatting a lengthy SQL query in a Node.js application

Currently, I am facing a challenge with a massive MySQL select query in my node.js application. This query spans over 100 lines and utilizes backticks ` for its fields, making me uncertain if ES6's multi-line string feature can be used. Are there any ...

Ending a timer from a different function in a React component

Currently, I am delving into the world of React and attempting to create a timer component. While I have successfully implemented the start function for my timer, I am now faced with the challenge of stopping the timer using an onclick handler from another ...

Develop a custom autocomplete feature using Formik in React for selecting values from an array of objects

Looking to Add Autocomplete Functionality in Your React Application Using Formik for Seamless Selection of Single and Multiple Values from an Array of Objects? Take a Look at this Code snippet! [see image below] (https://i.stack.imgur.com/ekkAi.png) arra ...

Passing data from child to parent in Angular using EventEmitter

I have integrated a child grid component into my Angular application's parent component, and I am facing an issue with emitting data from the child to the parent. Despite using event emitter to transmit the value to the parent, the variable containing ...