How can I update a particular label with Ajax?

I have encountered an issue where I am attempting to dynamically update a label every 5 seconds using AJAX and interval in my Webforms application. However, the label only updates when I manually refresh the page. It does not change without reloading the page.

On the client side:

In my JavaScript code:

    setInterval(function () {
        function GetStatus() {
            $.ajax({
                type: "POST",
                url: "RunningConsolePage.aspx/GetStatus",
                data: '{name: "' + $("#<%=lblStatus.ClientID%>")[0].value + '" }',
                contentType: "application/json; charset=utf-8",
                dataType: "json",
                success: OnSuccess,
                failure: function (response) {
                    alert(response.d);
                }
            });
        }

        function OnSuccess(response) {
            $("#<%=lblStatus.Text=GetStatus()%>")
        }
    }, 5);

In my HTML:

<asp:Button ID="btnQArun" Text="QA" OnClick="btnQArun_Click" CssClass="btn btn-info btnSize" OnClientClick="Confirm('QA')" runat="server" />
<asp:Label ID="lblStatus" Text="Status" runat="server"/>

On the server side:

[System.Web.Services.WebMethod]
public static string GetStatus()
{
    Random random = new Random();
    const string chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
    return new string(Enumerable.Repeat(chars, 11)
      .Select(s => s[random.Next(s.Length)]).ToArray());
}

Answer №1

Make sure to adjust your methods outside of the interval, then call them within the interval. Remember, the time is in milliseconds, so 5 does not equal 5 seconds but rather 5 milliseconds.

<script>
    setInterval(GetStatus, 5000);

function GetStatus() {
            $.ajax({
                type: "POST",
                url: "RunningConsolePage.aspx/GetStatus",
                data: '{name: "' + $("#<%=lblStatus.ClientID%>")[0].value + '" }',
                contentType: "application/json; charset=utf-8",
                dataType: "json",
                success: OnSuccess,
                failure: function (response) {
                    alert(response.d);
                }
            });
        }
        function OnSuccess(response) {
            $("#<%=lblStatus.ClientID%>").text(response.d);
        }
</script>

Remember: 1000 ms = 1 second.

Don't forget to correct the selector in the OnSuccess method if it's incorrect. Once you make that change, everything should work smoothly.

For more useful information, visit: https://javascript.info/settimeout-setinterval

Cheers,

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

Utilizing Yii2 for form validation and submission using AJAX

Seeking guidance on AJAX integration in Yii2, I've turned to this platform for assistance... Can anyone provide insight on how to create and submit a form with AJAX validation in Yii2? I've tried conducting my own research but haven't been ...

Creating a custom Jquery function to generate a Div element instead of a Textbox in your web application

I need assistance with a jquery function that retrieves data from a JSON PHP MySQL setup. The retrieved results are currently displayed in textboxes. function showData(wine) { $('#Id').val(wine.id); $('#question').val(wine.question ...

What is preventing the use of data post submission in React JS?

After posting data to the navigation, I retrieve it and then use the following code: .then(data => console.log(data.PathPDF)) .then(data => window.open(data.PathPDF, '_blank', 'noopener,noreferrer')); While I can successfully ret ...

Divide the parsed rss findings into separate parts

I am in the process of developing a project that involves aggregating job listings from various websites by parsing their RSS feeds. I am utilizing rss-parser for this purpose. Each feed has its own format for the title field, resulting in varying structu ...

After an ajax call in ASP .NET MVC3 using Razor, jQuery may not function properly

When I perform a post back to obtain a partial view using ajax, I utilize the following code to render the partial view within a div named 'DivSearchGrid'. <script type ="text/javascript" > $('#Retrieve').click(function ( ...

a single button with dual functionalities

I am new to the development field and have a question about jQuery. I want a single button to perform two different actions. For example, let's say we have a button labeled Pause/Resume. When I click on the button, it should first display "Pause", and ...

How to use ngModel directive in Angular to select/unselect dynamically generated checkboxes and retrieve their values

Currently, I am working with a dataset retrieved from an API and dynamically creating checkboxes in my HTML page using the DataView component from PrimeNG. My objective is to implement a feature where users can select or deselect all checkboxes with a cli ...

Tips for customizing the appearance of grouped rows in a Vuetify datatable with the use of slots

Has anyone successfully utilized grouped rows with v-slot in the most recent Vuetify versions? The example they provide is as follows: <template> <v-data-table :headers="headers" :items="desserts" item-key="name" group-by="categ ...

Utilizing Axios recursion to paginate through an API using a cursor-based approach

Is there a way to paginate an API with a cursor using axios? I am looking to repeatedly call this function until response.data.length < 1 and return the complete array containing all items in the collection once the process is complete. Additionally, I ...

Transform SVG with a Click

Can someone assist me with rotating the pink area on click and moving it to a new angle from its current position? I am looking for a way to save the current position of the pink area and then, when clicked, move it smoothly to a new position. Your help ...

What is the best way to verify the [routerLink] values displayed from an Angular component string array?

I want to display the [routerLink] values coming from a string array in my Angular component. This is the TypeScript code: import { Component, OnInit } from '@angular/core'; @Component({ selector: 'app-header', templateUrl: & ...

Guide to adding sound effects to your Vue 3 app using the Composition API

I'm having trouble setting up a basic button click feature in Vue 3 Composition API to play a sound effect. In my setup function, I have imported an mp3 sound effect from the assets folder and passed it into a ref method with an HTMLAudioElement type, ...

Using jQuery to manipulate XML: Altering XML content using its ID with jQuery

Trying to modify content within an XML using jQuery has been a bit tricky for me. Based on the examples I've found, I believe the code should look something like this: Javascript: get_verrichtingen: function(){ var self = this; var option = ...

The insertion of the script string from the ajax response was unsuccessful

When working with PHP, I encountered an array with two parts: array('threeRowHtml'=> '<HTML output string>', 'jsCode'=> '<script output string>' ) I decided to return this array for my ajax call. ...

Add integer to an array of strings

Currently, I am utilizing an autocomplete feature and aiming to save the IDs of the selected users. My goal is to store these IDs in a string array, ensuring that all values are unique with no duplicates. I have attempted to push and convert the values u ...

How to create a sequence of queries to a mongoDB database (using mongoose) depending on a condition

Source Code let placeForSearch="hampi" let filteredHotelFacilities=req.body.filter //["Free Wifi"] let hotels = await Hotel.find({placeForSearch}) .where("facilities") .select(selectedProperties) .skip(pageNu ...

Generating dynamic elements using information from a JSON dataset

My goal is to populate my webpage with card divs that contain data retrieved from a recordData.json file. Here is an example of what each card div should look like: <div class="card text-center bg-dark cardBorder" style="width: 18rem;"> <img ...

Using Regular Expression in JavaScript to replace variables within a string

Looking for assistance to replace keywords in a string with pre-defined variables. Currently, the code only displays variable names instead of their content. Can anyone provide help? Desired Output: 1111Test1 2222Test2 3333Test3 Current Output ...

What is the best way to send two mongoose find queries to the correct GET route?

I am facing an issue with my app where I have two separate routes using app.get to render "/" and fetch data from two different MongoDB collections using mongoose find{} methods. I also have corresponding post routes that redirect the data entered in forms ...

Animating jQuery Counter with Changing Background Color

I've implemented a Counter that counts from 0 to a specified number, and it seems to be working perfectly. However, I want to add an animation where the background color of a div height animates upwards corresponding to the percentage of the counter. ...