Refresh the Javascript Gauge exclusively, without affecting the entire page

I need assistance with updating a JavaScript Gage that showcases a percentage and refreshes every 5 seconds on an ASPX page. Currently, I am refreshing the entire page, but I understand that this is not ideal practice. Could someone guide me on how to specifically refresh only the JavaScript Gage within the div gg11? I am relatively new to JavaScript, so any help on achieving this would be greatly appreciated.

ASPX

 <div id="gg11" class="gauge"></div>
 <meta http-equiv="refresh" content="5; URL=http://localhost:63738/main.aspx">

ASPX.cs

    protected void Page_Load(object sender, EventArgs e)
    {         
        JavaScriptMethod();           
    }

    protected void JavaScriptMethod()
    {
        Calculations();
        StringBuilder sb = new StringBuilder();

        sb.Append("<script>");
        sb.Append("var gg1 = new JustGage({");
        sb.Append("id: \"gg11\",");
        sb.Append("donut: 0,");
        sb.Append("title: \"LAKE WALES\",");
        sb.Append("titleFontColor: \"#000000\",");           
        sb.AppendFormat("value: {0},", percent);
        sb.Append("min: 0,");
        sb.Append("max: 100,");
        sb.Append("labelFontColor: \"#000000\",");
        sb.Append("humanFriendlyDecimal: 1,");
        sb.Append("decimals: 1,");
        sb.Append("symbol: \"%\",");
        sb.Append("startAnimationType : \"bounce\",");
        sb.Append("refreshAnimationType: \"bounce\",");
        sb.Append("startAnimationTime: 1000,");
        sb.Append("gaugeWidthScale: 1.2,");
        sb.Append("customSectors: [{color: \"#ff0000\",lo: 0,hi: 79}, {color: \"#ffa500\",lo: 80,hi: 89}, {color: \"#1eae1e\",lo: 90,hi: 100}],");
        sb.Append("counter: true");
        sb.Append("});");
        sb.Append("</script>");

        ScriptManager.RegisterStartupScript(this.Page, this.GetType(), "temp", sb.ToString(), false);
    }

Answer №1

To create an interactive gauge on your webpage, you can utilize a blend of JavaScript, jQuery, and ASP.NET AJAX Page Methods. Here's how:

Begin by adding the necessary markup:

<div id="gaugeContainer" class="gauge"></div>

Next, implement the following JavaScript code:

$(document).ready(function() {
    setInterval(updateGaugeData, 5000);
});

function updateGaugeData() {
    $.ajax({
        type: "POST",
        url: "YourPage.aspx/RetrieveGaugeData",
        data: "{}",
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        success: function(response) {
            if (response.hasOwnProperty("d")) {
                $('#gaugeContainer').html(response.d);
            }
            else {
                $('#gaugeContainer').html(response);
            }
        }
    });
}

Note: Replace `YourPage.aspx` with the actual name of your .aspx page. The presence of `.d` in the response structure is a security feature introduced by Microsoft in ASP.NET 3.5 for protection against XSS.


In the code-behind file, include the following method:

[WebMethod]
public static string RetrieveGaugeData()
{
    GenerateGaugeValues();
    StringBuilder sb = new StringBuilder();

    // Construct the script to initialize JustGage
    sb.Append("<script>");
    sb.Append("var gauge = new JustGage({");
    sb.Append("id: \"gaugeContainer\",");
    sb.Append("min: 0,");
    sb.Append("max: 100,");
    sb.AppendFormat("value: {0},", percentage);
    sb.Append("labelFontColor: \"#000000\",");
    // Additional gauge configurations here
    sb.Append("});");
    sb.Append("</script>");

    return sb.ToString();
}

Answer №2

To utilize the javascript setInterval function, initiate an ajax call to your server. This will prompt your server page to furnish the specific HTML content you desire without refreshing the entire page.

Assuming jQuery is present on your page,

$(function(){

  var intervalId = setInterval(function(){ 
                         $("#gg11").load("getgauge.aspx");}, 5000); 

});

Subsequently, this will consistently dispatch an ajax request to the server page at 5-second intervals. Ensure that getgauge.aspx returns the HTML markup intended for display in the UI.

If your goal is to monitor only updated values (whenever a value changes on the server), consider utilizing libraries like SignalR for seamless real-time communication.

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

Is it possible to incorporate variables when updating an array or nested document in a mongodb operation?

Within the "myCollection" target collection, there exists a field named "japanese2". This field is an array or an object that contains another object with a property called "japanese2a", initially set to 0 but subject to change. My goal is to update this p ...

When the TAB key is pressed with an empty text field, ASP.NET should display a validation message indicating that the field is required

Typically, required field validation occurs on button clicks. However, I would like the alert to be displayed when moving to the next TAB index instead. How can I achieve this using JavaScript and ASP.NET? ...

What is the reason for needing to multiply all the numbers by ten in order to solve this floating point addition problem?

When dealing with floating point arithmetic in Javascript, it's common to see results like 0.2 + 0.1 = 0.30000000000000004, which can be confusing. However, a simple workaround is to multiply the numbers by 10, perform the operation, and then divide b ...

Encryption of Publication Profile

I am looking to secure my connection string and app settings by encrypting them. Currently, I manage multiple publish profiles, each with its own transformation settings. Below, you will find the code snippet from my pubxml file. However, I am facing an i ...

Issue with MVC framework: AJAX query callback function not functioning properly

Struggling with implementing a basic Jquery Ajax callback: Here is my Jquery code snippet: $(document).ready(function () { $('#btnClient').click(function (e) { e.preventDefault(); var txtClient1 = $('#txtCli ...

Is there a way to display only the first x characters of an HTML code while disregarding any tags present within

When I work with a text editor, it generates HTML code that I save in the database. On another page, I need to display only the first 100 characters of the text without counting the HTML tags. For instance, let's say this is the HTML code saved in th ...

Turn off Jquery Mobile Ajax Navigation

After countless hours spent poring over API documentation and online forums, I still can't seem to disable the AJAX Navigation feature. CURRENT SETUP <script src="http://code.jquery.com/jquery-1.10.2.min.js"></script> <script src="htt ...

Below is a compilation of items found within the JavaScript object that include the data from the previous list

I am currently experiencing an issue where the values in the list of objects within some object only contain values from the last object. My goal is to assign scores to locations based on various criteria (which are stored in a separate list). To simplify ...

Changes made to code within the node_modules directory do not appear in the browser

I encountered a bug in the vuejs-datepicker project on Github, prompting me to fork the repository. However, despite making changes to the forked project, these alterations are not reflected in my main project that relies on this dependency. Here's a ...

Finding the least common multiple (LCM) of two or three numbers using JavaScript

I have been working on a code snippet to find the Greatest Common Denominator (GCD) of two or three numbers. Here is what I have so far: Math.GCD = function(numbers) { for (var i = 1 ; i < numbers.length ; i++){ if (numbers[i] || numbers[i] = ...

Exploring the hover functionality in GetOrgChart

Exploring mouse hover functionality in Getorgchart view. Looking to implement the mouse hover and mouse out events in Getorgchart view. Can I access the org chart element details during mouse hover/leave actions? ...

``Troubleshooting Problem with Tailwind's Flex Box Responsive Grid and Card Elements

Starting point: Preview https://i.sstatic.net/zfzBU.jpg Code : <div class="container my-12 mx-auto"> <div className="flex flex-wrap "> {error ? <p>{error.message}</p> : null} {!isLoading ...

What is the best way to showcase a set of 10 random records from a database

Is there a way to randomly select and display 10 questions from a database? How can I verify if the answer is stored correctly in the database? db.execute(true, "SELECT * FROM question WHERE Category='" + choice + "'"); foreach (DataRow record ...

How can I ensure that my asynchronous code is consistently executed on the same thread within a native node module?

In the process of developing a native node module in C++, I am creating a binding for a C library. It is crucial to note that certain objects within this library should only be accessed by a single thread. However, using uv_queue_work presents a challenge ...

A guide to incorporating tab functionality into a partial view using ASP MVC

I am facing some challenges on how to implement tabs within an MVC project. The issue at hand is that I want to have tabs in a partial view, but I also need them to be accessible across all controllers and views. As I work on creating these tabs, I will re ...

Employing a one-time use variable that is asynchronously loaded via a React hook

Currently, I am exploring the functionalities of React's hooks, but I'm encountering a roadblock when it comes to integrating different use cases. The main goal is to create a hook called useNationsAsync that fetches a list of available nations ...

Repetitive horizontal Google Maps marker on ImageMapType

<!DOCTYPE html> <html> <head> <title>Custom Image Mapping</title> <style> html, body, #map-canvas { height: 100%; margin: 0px; padding: 0px } </style> <scrip ...

Having difficulty invoking a function from an external JavaScript file

Clicking on a button triggers the function showDiv(). The showDiv() function is defined in an external JavaScript file named script.js. When using an external script file, the showDiv() function does not get called. However, placing the script in the sam ...

What could be causing my Boolean to not receive the intended value?

Here is some ASP.Net code I am working with: <select name="subcategory" color="<%=Session("TextColor")%>" style="font: 8pt arial" onchange="UpdateFlag=true;"> <% if not IsNewBusiness then %> <option value="0">Existing ...

Interacting with the header component within the renderHeader property of the MUI Data Grid Pro will update the sortModel

Currently, I am utilizing the Material UI DataGridPro component to construct a React Js application. I am interested in developing a customized filtering feature. In the image below, you can see a red box representing an IconButton for the filtering view ...