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

Endless invocation of AngularJS $http requests

Could someone kindly clarify why the $http request is continuously sending an infinite number of requests to the server in my application? The code snippet provided is causing this issue: (function(){ var app = angular.module("GrahamsSocksProducts", [ ...

Show a Pair of Images Upon Submission Utilizing Ajax

Imagine having two separate div containers displayed as shown below: What I achieved was clicking the submit button would upload the image to the designated area. However, my goal is for a single click on the button to load the image in both containers. ...

Angular $watch | obtaining the result from a function

I'm curious why I consistently have to use this $scope.$watch( function() { return $scope.someData; }, function( value ) { console.log( value ); }); in Angular in order for it to watch the data. It's frustrating to me because it seems un ...

Prevent financial disagreement by utilizing jQuery carefully

While I'm sure this question has been asked in a similar form before, my searches for the $ sign did not return any results here. I have already built a large system and heavily utilized jQuery, using $ as a reference. Now, I don't want to rever ...

Parsing JSON data on the client side in an ASP.NET application

I am currently working with JSON data that looks like this: "Table":[ { "AF":2000.00 "RegionNumber":1 "RegionName":"Black Sea" }, { "AF":100.00 "RegionNumber":1 "RegionName":"Black Sea" }, { "AF":15000.00 "RegionNumber":2 "RegionName":"Ista ...

"Sweet syntax" for assigning object property if the value is true

In the project I'm working on, I find myself dealing with a lot of parsing and validating tasks. This often results in 5-10+ lines of code like if(value) object.value = value. I considered using object.value = value || (your favorite falsy value) app ...

Error in tabs.onUpdated argument in Firefox WebExtensions

I am currently working on developing a straightforward webExtension for Firefox and I would like to implement tabs.onUpdated with a filter. I found an example on the Mozilla website that I decided to use: const pattern1 = "https://developer.mozilla.org/*" ...

Tips for managing Ajax JSON response in a PhoneGap application

Although there are a few posts on this topic, I am struggling to piece together the necessary components to make it work. I am in the process of converting a web application into an app using phonegap and I am attempting to create a search form that retri ...

Implementing an Asynchronous Limited Queue in JavaScript/TypeScript with async/await

Trying to grasp the concept of async/await, I am faced with the following code snippet: class AsyncQueue<T> { queue = Array<T>() maxSize = 1 async enqueue(x: T) { if (this.queue.length > this.maxSize) { // B ...

NextJS configuration facing an issue with rewrite rules not functioning as intended

I have attempted to utilize a rewrite rule in the NextJS next.config.js file in order to redirect URLs containing '/lite' to '?amp=1', however, it does not seem to be functioning correctly in all scenarios. Below is the code from my ne ...

The function window.open() is experiencing difficulties when trying to open a file located in a subfolder

As someone who is new to programming, please excuse any lack of knowledge on my part, but I am having trouble finding the answer to this. I am currently using window.open() to open a .php file in a popup window and passing a variable through the URL to be ...

"Exploring the Mini Drawer feature on Material UI brings up a whole new page for the Link

Currently, I am working on a project that involves updating stocks using Material UI. I have implemented a mini drawer from Material UI, but when I click on the menu link, it routes to a new page instead of rendering on the homepage itself. In my App.JS f ...

Show specific button text when no file has been selected

I have a form with an image container that allows users to change the photo. The icon opens a file browser, and when the user selects a file, the Change button submits the photo and updates it. If no file is selected, I want to display the text "Select a ...

"Obtain a DOM element within an Angular directive by using the jQuery find method

When inspecting the DOM, I can see the element anchor tag present but cannot retrieve it using jquery.find(). The console returns a length of 0, preventing me from initializing angular xeditable on that element. angular.module('built.objects') ...

New to React and looking for guidance on implementing .forEach or .includes in my code

My task involves going through an array and checking if a string that the user inputs into the form exists in it. This can be achieved using forEach or .includes method. I am basically trying to filter out the array based on the input. If someone could de ...

What is the best way to single out a specific item from a list to display in a component upon clicking in Vue.js?

To view the data of a specific item in the child component "comandasInd", I just need to click on the icon. <template> <v-data-table :items="comandas"> <template v-slot:items="props"> <td>{{ props.item.nombre }}</td& ...

Utilizing optional parameters with React Router

Imagine I have a page at http://www.example.com/page/#/search set up with the following routing: <Router history={hashHistory}> <Route path='/search/' component={SearchPage} /> </Router> When a user performs a search using t ...

Improving the method of accomplishing a task using AngularJS

Clicking on an item in the tobeclicked list will transfer the data to the find empty list. The goal is to locate an empty list and update it by cloning the image there. The actual values and lists will include images. When an image is clicked, the system s ...

Tips for submitting multiple radio button values in a tabular format

HTML Code: <div class="tab"><h4>Zip Code</h4> <p><input type="text" class="text1" placeholder="Enter zip code..." oninput="this.className = ''" name="zipcode"></p> </div> <div class="tab">& ...

Make the object rotate around a specified vector point

I have been trying to figure out how to make an object orbit around the vector coordinates 0,0,0. Specifically, if the object is at X300, Y50, Z200, I want it to revolve around 0,0,0 without changing the position on the Y axis. Math isn't my strong su ...