How to send data to JavaScript during a partial page refresh using an UpdatePanel

After performing a query in the code behind and storing the value in a hidden field, I am wondering how to pass that same value to Javascript without using session variables, as they do not update on partial page load.

This is the code snippet I currently have:

 <script type="text/javascript">
    google.load("visualization", "1", { packages: ["corechart"] });
    google.setOnLoadCallback(drawChart);
     //Draw a pie
    function drawChart() {
        var data = new google.visualization.DataTable();
        data.addColumn('string', 'Task');
        data.addColumn('number', 'Hours per Day');
        data.addRows(4);

        data.setValue(1, 0, 'Not Received');
        data.setValue(1, 1, Value1);
        data.setValue(2, 0, 'Received');
        data.setValue(2, 1, Value2);
        data.setValue(3, 0, 'Read');
        data.setValue(3, 1, Value3);
        var chart = new google.visualization.PieChart(document.getElementById('chart_div'));
        chart.draw(data, { width: 450,backgroundColor:'#DCDCDC', height: 300, title: 'Message Status' });

      // to draw a bar
        var progress1 = new RGraph.VProgress('progress1', Value4, 100);
        progress1.Set('chart.colors', [Value5]);
        progress1.Set('chart.tickmarks', false);
        progress1.Set('chart.margin', 3);
        progress1.Set('chart.tickmarks.inner', false);
        progress1.Set('chart.label.inner', true);
        progress1.Set('chart.gutter.left', 20);
        progress1.Set('chart.gutter.right', 40);
        progress1.Set('chart.tickmarks', true);
        progress1.Set('chart.units.post', '%');
        progress1.Draw();
        }           

I need to find a way to pass the value from the hidden field to the last line. Can you provide me with some example code for this?

Answer №1

If this code is executed at a specific time, you have the option to implement the following approach:

data.setValue(1, 1, "<%=ServerSideFunction()%>");

UPDATE

You mentioned that you are storing the value in a hidden field, so why not fetch the value directly from the HiddenField using JavaScript?:

JavaScript:

var value = document.getElementById("<%=HiddenField1.ClientID%>").value;

jQuery:

var value = $("#<%=HiddenField1.ClientID%>").val();

If you require a value that is only accessible after the page reloads, consider utilizing PageMethods.

Check out this article for guidance on utilizing PageMethods:

Answer №2

When it comes to sending server-side data to the client upon page load, there are a couple of effective methods you can utilize. You have the option of employing the .NET ScriptManager class to incorporate script directly onto the page or inserting it inline (e.g. using var value = <%= Value %>).

Take a look at this demonstration showcasing how to integrate script into your response using the ScriptManager:

Page.ClientScript.RegisterStartupScript(Me.GetType(), Me.GetType.Name(), script, True)

In this example, the variable script is a string containing the specific script that you wish to add to the page. Here's an illustration of what the content of script could look like:

"var data = 1234"

Subsequently, it will be included in the response of your page (within the form element) similar to this:

<script>var data = 1234</script>

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 there a way to pause the slideshow? Are there any ways I can enhance the code to make it more efficient?

Currently, I am testing a slideshow that automatically transitions every 1 second. I have set it up to pause when it reaches the first image. However, when it stops on the initial image and I click the next button, nothing happens. If I try to interact wit ...

Utilizing JavaScript for parallax horizontal scrolling (identifying optimal 50% of screen)

I have successfully implemented this code for vertical scrolling: $('.flapleftclass').css('top',(0+(scrolled*0.5))+'px'); This method works well because I am referencing to the top position. However, when it comes to horizon ...

Converting an object to a string array in C# may lead to an error when switching from `*` to `[]`. Having knowledge of both VB

Currently, I am facing a challenge with converting a VB.NET project to C#. The specific issue lies within the usage of a class named RsiOPCAuto. Although the intricacies of how this class operates aren't crucial for this discussion, I would like to ad ...

The word-break CSS property is ineffective in this situation

I've been experimenting with the word-break css property, but I just can't seem to get it to work even when using a simple example. Here's my code: React: render() { return ( <h5 className="word-break">A very very long line.... ...

The parental context is not bound to the isolated scope of the custom directive

Below is the custom directive implemented: (function() { angular.module('commentsDirective', []) .directive('mngComments', mngComments) function mngComments() { return { restrict: 'AE', ...

Is your Ajax response suddenly failing to work after the initial attempt?

Describing my predicament: The code snippet below is what I have been using to insert a custom-designed div into my webpage. Initially, the div is successfully added; however, it stops working after the first instance. $('#addanother').click(fu ...

Optimize Date Formatting within a React Application Using Material UI Data Grid

I am currently working with MUI Data Grid Pro and I have an issue with filtering dates in the format dd-mm-yyyy. While the dates are displayed correctly in the columns, the filtering defaults back to mm-dd-yyyy. https://i.stack.imgur.com/Ue12K.png For mo ...

I am attempting to pass information through the body of an Axios GET request to be used in a Django backend, but when I try to print the request.body

As reported by Axios, it seems that this is a feasible solution: https://github.com/axios/axios/issues/462#issuecomment-252075124 I have the code snippet below where pos_title contains a value. export function getQuery(pos_code, id) { if (id === 94) ...

Is there a way to incorporate multiple conditions into the ternary operator in React Native?

When the item is of diaryClass.name "pack" in react native, if diaryId is 778 I want to render chicken, 776 renders burger, and 775 renders pizza. However, my code only displays the chicken value while burger and pizza are not displayed. How can I correct ...

Generate a list of JS and CSS paths for UglifyJS/UglifyCSS by parsing an HTML file

Seeking a tool that can scan an HTML file (specifically a Smarty template file) to extract paths from <script></script> and <link/> tags for use with UglifyJS/UglifyCSS or similar minification tools. Extra credit if it can handle download ...

An unexpected issue occurred: AngularJS module error prevented from functioning properly

I'm attempting to set up a Modal popup when an image is clicked using Bootstrap Lightbox, but I can't seem to get it working. I've followed an example with the exact same code provided below. I have downloaded the Lightbox components (*.ligh ...

I'm encountering a type error stating that children are not defined when attempting to establish parent-child relationships from a flat array. What

Trying to establish a parent-child relationship between modules based on their IDs. Ran into an issue with the function I used, as it returned an error stating that children were not defined. const data = [ { module_id: "96ac027b-b5ce-4326-b5db- ...

Encountering a post route error when utilizing async await has hindered my ability to add a new product

Recently, I attempted to update my post route using async await, and unfortunately made some mistakes. Now I'm unsure how to correct it properly. router.post('/', async (req, res, next)=> { try{ const updatedProduct = await ...

How can you dynamically disable a radio option button using Angular rendering without relying on an ID?

Is there a way to disable the male radio button without using an id, and utilizing angular rendering2? It seems like it's not working for me. I need to make this change only in the form.ts file, without altering the HTML code. form.html <label& ...

How can you trigger an alert and refresh the page at the same time upon receiving a Firebase response?

Presently, my method involves utilizing Firebase to store data. Upon receiving a response from Firebase, I aim to display an alert message and then refresh the form page. Below you can find the code snippet that I am currently working with: // Save new in ...

Learn how to retrieve a jqGrid ajax Nested Array of Json string in C# using Newtonsoft Json

I am attempting to parse a JSON string and extract the array values within it. {"_search":true,"nd":1492064211841,"rows":30,"page":1,"sidx":"","sord":"asc","filters":"{\"groupOp\":\"OR\",\"rules\":[{\"field\":\ ...

Utilizing the jQuery library for flexible REST API requests with the incorporation

I'm currently utilizing jQuery getJSON to fetch posts from the WP API v2. There are some input fields that I'd like to make clickable, and then add extra parameters to the request URL. Here are some example requests: Posts - https://www.example ...

Refreshing the page allows Socket.io to establish multiple connections

I've been working on setting up a chatroom, but I've noticed that each time the page refreshes, more connections are being established. It's interesting because initially only one connection is created when I visit the chat room page. Howeve ...

Failure to update labels within jQuery dialog triggered by async postback

My .aspx file contains the following elements: In my .aspx file: The update panel below includes a button that is used to open a dialog box. <asp:UpdatePanel ID="UpdatePanel" runat="server" UpdateMode="Conditional" ChildrenAsTriggers="true" RenderMod ...

Utilizing the Public Directory in Vite Compilation

One issue I encountered in my project with Vite version 2.9.7 is related to the handling of images stored in the public folder within the project's root directory. To import these images, I utilized Vite's import.meta.glob function, like so: imp ...