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

Switch between different react components

When a component is opened, I want all other components to close. Whenever they are clicked, they will display a list. class ParentComponent extends Component{ constructor(props){ super(props) this.state= {...} } render(){ return( ...

Discover the ultimate guide on developing a personalized file management system using the powerful node.js platform!

I have undertaken a rather ambitious project for myself. There exists a comprehensive tutorial on the website that outlines the process of establishing an online environment (resembling a user panel) where registered users can effortlessly upload various ...

Unable to retrieve a response, the operation `users.findOne()` has exceeded the buffering time limit of 10000ms

I encountered an issue when attempting to make a POST login request. The frontend is deployed on Netlify here, and the backend is deployed on Heroku here. Here are my backend logs . I am receiving `users.findOne()` buffering timed out after 10000ms in ...

tips for optimizing javascript file caching

https://i.stack.imgur.com/UhWD1.pngMy web application was created using "pug" technology about 9-8 years ago, and more recently, pages have been added in an innovative framework (vue.js). However, whenever there is a transition between an old pug page and ...

Is it possible to display a complete list of my items along with their parameters using jQuery ajax?

My function code is set up to display all the items from my list of discipline codes, but I'm facing issues viewing them due to data:{params} always being present. alert('Could not retrieve data'); Any assistance would be greatly appreci ...

How can I make multiple elements change color when hovering with CSS?

Hey there! I have a little design challenge that I need help with. On my website (), I am trying to make multiple elements of a specific item change color when the user hovers over the text. If you hover over the "more" menu item, you'll notice that o ...

An observer is handed to me when I receive an array as a parameter

How can I use an array as a parameter instead of just receiving an observer? When trying to utilize the array, all I get is an observer. The data appears correctly when using console.log in the function that fetches information from the DB. Despite attem ...

When a specific condition is met, Jquery can automatically execute a function contained

I am trying to slowly reveal the h1 tag using jQuery for demonstration purposes. The scroll function is working when I manually click to initiate it, but I am having trouble triggering it automatically. I feel like I might be missing something simple and ...

Utilizing NodeSize to Optimize the Spacing Among Nodes in the D3 Tree Arr

Currently, I am trying to adjust the positioning of my rectangle nodes because they are overlapping, as illustrated in the image below: In my research, I discovered that D3 provides a nodeSize and separation method. However, I encountered difficulties imp ...

Is it better to use AngularJS' ngMock inject before each test or for each individual test case?

Current Situation As I work on writing tests for an Angular project, I have come across a common practice of creating "global" variables in a describe block to store dependencies needed for the tests. This approach involves defining variables like $contro ...

Apply various filters to extract and refine information from the database

I have successfully retrieved data from the database. The structure of the data is as follows: serie --- title (string) --- category (array) To filter the data, I have implemented a search filter using a computed property. This is how it looks: f ...

When setting an empty URL with Fabricjs' setBackgroundImage function, a null reference error occurs in the _setWidthHeight

Recently, I stumbled upon an article detailing a method to clear the background of a fabric canvas... canvas.setBackgroundImage('', canvas.renderAll.bind(canvas)); In the development of my online design tool which utilizes Fabricjs 1.4.4, I have ...

Utilizing JQuery for real-time total updates

When a new div is created by clicking a button, I want to dynamically maintain an order system where the first div is labeled as 1 of 1, then as more divs are added it should change to 1 of 2, and so on. If a div is deleted, the numbering should reset back ...

What are the benefits of incorporating an external API with Next.js API routes?

I've recently started using Next.js and I'm curious about the purpose of export default function handler since we can directly fetch data from APIs. In my HTML code, I have the following snippet. When the submit button is clicked, the sendformDa ...

Troubleshooting: Resolving issues with Vue's global EventBus in my project

I am using Vue.js within a Laravel project and I am encountering an issue with the global event bus. I have created an event-bus.js file and imported it where needed. Although events are being generated upon clicking, there seems to be no reactions from th ...

Issue with ExpressJS Twig module: inability to execute async functions even after adjusting settings as needed

Currently, I am facing an issue while trying to load an array from mongoose into a twig rendered list. An error message keeps popping up: TwigException: You are using Twig.js in sync mode in combination with async extensions. I have made sure to care ...

Tips for showcasing the chosen option from an autocomplete input field in a React application

Currently learning React and working on a search feature for a multi-form application. The goal is to allow users to search for a student by first name, last name, or student ID using an autocomplete text field. The options for the autocomplete text field ...

The Web Browser is organizing CSS elements in an alphabetized sequence

map.css({ 'zoom': zoom, 'left': map.width()/(2*zoom) - (point[0]/100)*map.width(), 'top': map.height()/(2*zoom) - (point[1]/100)*map.height() Upon observation, it appears that Chrome adjusts the map zoom first be ...

Guide to retriecing a state in Next.js 14

Check out my code below: "useState" // firebase.js import firebase from "firebase/app"; import "firebase/auth"; // Import the authentication module export default async function handler(req, res) { if (req.method !== " ...

What is the best way to incorporate Tradingview's JavaScript into the render function of a React Typescript

I'm trying to incorporate some widgets into my Typescript React component. Here is the embed code export default class App extends React.Component { render(): ReactNode { return ( <div> Chart test <div className= ...