Utilizing an Ajax request for a polling system

I am in need of adding a polling mechanism to call a web service from my webpage. To achieve this, I am attempting to utilize an ajax call within a javascript page. However, I am fairly new to both ajax and javascript. Below is the code snippet that I have written.

<html>
<head>
    <script language="JavaScript" type="text/javascript">
         function pollServerForNewMail() {
            setTimeout(function(){
            $.ajax({ url: "server", success: function(data){
                alert("TEST");
                poll();
            }, dataType: "json"});
        }, 10000);
</script>
</head>
<body>

</body>
</html>

My goal is to trigger the display of the alert message "TEST" every 10 seconds. Can anyone provide assistance with this task?

I will update the post with my two jsp files.

index.jsp file

<html>
    <table style="width:100%;text-align:center;'">
<tr>
<td style="text-align:center;width:100%">                               
<a href="polling.jsp?reset=true"><img src="images/import.png" /></a>
</td>
</tr>
</table>
</html>

polling.jsp file

         <html>
            <head>
                <script language="JavaScript" type="text/javascript">
                     function pollServerForNewMail() {
                        setTimeout(function(){
                        $.ajax({ url: "server", success: function(data){
                            alert("TEST");
                            poll();
                        }, dataType: "json"});
                    }, 10000);
}
        pollServerForNewMail() ;  

          </script>
            </head>
            <body>
       </body>
        </html>

Thank you

Answer №1

setTimeout function triggers a timer one time only.

To perform a task at regular intervals, you can use setInterval:

function checkForNewMessages() {
    setInterval(function(){
        // This code block will be executed every 10 seconds

        $.ajax({ url: "server", success: function(data){
            alert("NEW MESSAGE RECEIVED");
            updateInbox();
        }, dataType: "json"});
    }, 10000);
}

Answer №2

After making changes to the polling.jsp file, I was able to resolve my issue successfully by implementing the following modifications.

<html>
    <head>
        <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>
        <script>
            var set_delay = 5000,
                    callout = function () {
                        $.ajax({
                            /* place your code here */
                        })
                                .done(function (response) {
                                   alert("TEST");
                                })
                                .always(function () {
                                    setTimeout(callout, set_delay);
                                });
                    };
            callout();
        </script>
    </head>
    <body>

    </body>
    </html>

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

Issue with express-session failing to retain set variables following server-side ajax request (to Spotify API) through the request module

I am in the process of developing a website dedicated to categorizing music genres and for this purpose, I require integration with the Spotify API. Upon authorization, I set the session.loggedIn and other variables as desired values. However, I encounter ...

tips on displaying textbox content on a php webpage

I have a piece of code where, when text is entered into a textbox and the add attribute button is clicked, the entered value is displayed on the page twice. One appears in the first row of a table, and the other appears in the first row of a second table. ...

Encountering an Unexpected Error in Next.js When Revalidating Paths

I'm facing an issue with my Next app where, despite editing a resource through an API endpoint following the pages-based system, the changes aren't reflected when I try to view or re-edit the resource. After checking the documentation, I discover ...

Troubleshooting jQuery AJAX Errors in Internet Explorer 8

I've created a rather simple ajax call using jQuery. It's functioning flawlessly in IE9, the latest Firefox, and the latest Chrome, which leads me to believe that the page being posted to is working fine. However, it fails in IE8 (I haven't ...

Shifting JSON Arrays in JavaScript - Changing Order with Ease

Consider the following JSON data: [ { "name": "Lily", "value": 50 }, { "name": "Sophia", "value": 500 }, { "name": "Ethan", "value": 75 } ] I am looking to verify and organize it in ...

JavaScript code encounters difficulties parsing HTML source

I'm attempting to reconstruct the WhateverOrigin service, which can be found at this link: Nevertheless, when I try running it in my web browser, this code that functioned perfectly with WhateverOrigin no longer functions properly with my imitation s ...

When attempting to pass data to another page by clicking on a row, the result is that the data appears to be empty

I have been using the MUI-Datatable component, which is able to navigate to the next page. However, when I try to view the data on the History page, nothing appears. How can I resolve this issue? Data transfer to another page: Even though I can see the d ...

How can constants from components be defined in multiple ways when imported? (specifically in React)

Although I have a good understanding of React and Javascript, I struggle to articulate my question effectively. I will provide examples in the hopes that someone with more expertise in the field can assist me. For instance, when using import { useRef, use ...

Tips on adjusting the pixel dimensions of an image using a file object

Within a form on our website, users have the ability to upload an image file. To ensure quality control, I've set up validation to confirm that the uploaded file is either an image or gif format. In addition to this, I'm looking for a solution th ...

Utilizing Node.js with Redis for organizing data efficiently

Currently, I am in the process of configuring a Redis cache system for storing incoming JSON data in a specific format. My goal is to create an ordered list structure to accommodate the large volume of data that will be stored before eventual deletion. Th ...

It is not possible to make a comparison between two Strings within a JSP file

I have this unique JSP file that contains the following code: <SELECT name="brandsFrom" onchange="as()"> <c:forEach items="${brandsSelectedList}" var="brands"> <c:if test="${brands.name == nam}"> <option value="${b ...

ReactJS does not trigger a re-render when changes are made to CSS

I'm curious about the reason why ReactJS does not automatically reapply CSS to child components even when componentDidUpdate() is called. I conducted a small demo where adding a new box doesn't change the color of existing boxes, even though the ...

Capture all Fetch Api AJAX requests

Is there a way to intercept all AJAX requests using the Fetch API? In the past, we were able to do this with XMLHttpRequest by implementing code similar to the following: (function() { var origOpen = XMLHttpRequest.prototype.open; XMLHttpRequest.p ...

Execute iMacros Loop and terminate the process before proceeding to the next command

As a newcomer to the world of iMacro scripting, I am struggling with setting up a simple data scrape. I'm looking for guidance on how to create a loop for the following commands: URL GOTO=link1 URL GOTO=link2 URL GOTO=link3 WAIT SECONDS=7.5 Once th ...

What is the best method for incorporating line breaks into JSON output?

Here is the ajax code snippet that returns a single line like this: appleorangebanana My goal is to display it as clickable links in a list like this: apple orange banana I'm still learning about ajax and json, so any help ...

Issue encountered when attempting to send quotation marks to the web service using AJAX

Using .ajax, I am sending data with the following attributes: data: '{ "UserInput" : "' + $('#txtInput').val() + '","Options" : { "Foo1":' + bar1 + ', "Foo2":' + Bar2 + ', "Flags":"' + flags + '", "Im ...

Tips for compressing user data in JavaScript prior to transmitting it to the server using zip/gzip technology

As a Javascript novice, I am facing a challenge with multiple users sending large JSON payloads to the server. To reduce traffic, I want to compress them using gzip. Can gzip compression be implemented in Javascript? How can I convert the JSON string int ...

Enhancing webpage design by dynamically changing borders and headers using JavaScript

I have implemented a fixed positioning for the table headers using the following code: onScroll={() => { document.querySelector('thead').style.transform = `translate(0,${this.scrollRef.scrollTop}px)`; }} However, when I scroll the ta ...

Refresh the DIV by populating it with data retrieved from an AJAX call

My inquiry is regarding two divs: one containing an @ajax.beginform and the other being empty but hidden. I am trying to implement a scenario where the form in the first div makes an ajax request, and the action method of the controller checks if the model ...

Tips for modifying the background color of all elements ahead of the element I have selected within a grid

https://i.stack.imgur.com/cW4Lp.png I'm trying to achieve a functionality where clicking on the 20th numbered block changes everything before it to light orange. I have a sandbox code snippet attached and would appreciate any guidance on what needs t ...