Trouble with Google Interactive Charts failing to load after UpdatePanel refresh

Desperately seeking assistance! I have spent countless hours researching this issue but have hit a dead end. My dilemma involves using the Google Interactive Charts API within an UpdatePanel to dynamically update data based on dropdown selection changes. However, whenever the UpdatePanel refreshes, the chart suddenly disappears. I've confirmed that JavaScript executes within the updated panel by testing a simple alert, so the problem seems specific to how the Google javascript functions after the update. Could it be that the setOnLoadCallback fails to call drawChart post-UpdatePanel refresh? I'm uncertain if this is the root cause or how to rectify it.

The following code resides in a Public Sub called during Page_Load and when the selected value of the dropdownlist changes:

    Dim strOutput As New StringBuilder

    strOutput.Append("google.load('visualization', '1.0', { 'packages': ['corechart'] });")
    strOutput.Append("google.setOnLoadCallback(drawChart);")
    strOutput.Append("function drawChart() {")
    strOutput.Append("var data = new google.visualization.DataTable();")
    strOutput.Append("data.addColumn('string', 'Domain');")
    strOutput.Append("data.addColumn('number', 'Value');")
    strOutput.Append("data.addRows([")

    Dim sqlSelect As New SqlClient.SqlCommand
    sqlSelect.CommandText = String.Format("spAnalytics_ViewsByDomain")
    sqlSelect.CommandType = CommandType.StoredProcedure
    Dim dtChartData As DataTable = clsDB.FillDT(sqlSelect)

    Dim commaCounter As Integer = 1
    For Each row As DataRow In dtChartData.Rows
        If ddlStat.SelectedValue = "hits" Then
            strOutput.Append(String.Format("['{0}',{1}]", row.Item("domain"), row.Item("hit_count")))
        ElseIf ddlStat.SelectedValue = "sessions" Then
            strOutput.Append(String.Format("['{0}',{1}]", row.Item("domain"), row.Item("session_count")))
        End If
        If commaCounter <> dtChartData.Rows.Count Then strOutput.Append(",")
        commaCounter = commaCounter + 1
    Next

    strOutput.Append("]);")

    strOutput.Append("var options = { 'title': 'Views by domain',")
    strOutput.Append("'width': 500,")
    strOutput.Append("'height': 300")
    strOutput.Append("};")
    strOutput.Append("var chart = new google.visualization.PieChart(document.getElementById('chart_div'));")
    strOutput.Append("chart.draw(data, options);")
    strOutput.Append("}")

    ScriptManager.RegisterStartupScript(litDomains, GetType(String), "blahblah", strOutput.ToString, True)

Answer №1

Instead of including google.setOnloadCallback, simply insert a direct call to the function towards the conclusion.

Answer №2

Encountering a similar issue with Firefox specifically, I struggled to get the chart to redraw correctly in other browsers like Chrome, IE, and Safari. After some experimentation, I stumbled upon a workaround that, while unconventional, did the trick for me.

To address the problem in Firefox, I resorted to implementing a setTimeout of 10ms around the code responsible for redrawing the chart.

Another solution I came across involved replacing the UpdatePanel with JS AJAX, but I opted for the former due to its simplicity and effectiveness in my case.

Answer №3

I recently ran into a similar issue while working with google charts in combination with an update panel, so I wanted to share the solution I found.

When using an update panel for asynchronous or partial refresh, there can be issues with javascript code breaking. You can learn more about the cause and solution in this helpful article: Update panel and jQuery issue.

To resolve the problem of partial refresh causing javascript code to break, you can simply add the following code alongside your existing code to re-apply the javascript functionality. This code will call the function responsible for drawing the chart after each async postback:

<script type="text/javascript>

    var prm = Sys.WebForms.PageRequestManager.getInstance();
    prm.add_endRequest(function (sender, e) {
        if (sender._postBackSettings.panelsToUpdate != null) {
            // Event triggered when Async Postback is completed.
        }

        // Call your function here that draws the chart
        drawChart();

    });

</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

Developing a stock exchange application in PHP that provides real-time updates

Seeking a solution for displaying real-time stock data on a webpage in a format similar to excel. The software provides continuous updates every second in excel format and I need the webpage to reflect these updates in real time. Any ideas on how to achi ...

Rails 4 application encountering issues with rendering views when making a $.ajax request

I am a beginner in Rails and I am in the process of sending model data to a controller method from JavaScript for rendering a list of results... function submitResults() { resultURL = "/result"; resultData = JSON.stringify(results); $.ajax({ typ ...

Navigating between sibling components in Angular 1.5 using the component router

Is there a way to use the new component router in Angular 1.5 to display the sibling component alongside the main one within the ng-outlet directive? I am looking to showcase both the Detail View and the List View at the same time. Based on my understandin ...

What is the best way to determine the normals of a closed shape in three.js?

I am currently developing a custom mesh importer for my proprietary file format. The challenge I'm facing is that the format does not include normal data. As a result, I am exploring methods to calculate normals for enclosed shapes and then apply thos ...

Tips on invoking Bootstrap's collapse function without using JQuery

We are facing a challenge with our TypeScript files as we have no access to jQuery from them. Our goal is to trigger Bootstrap's collapse method... $(object).collapse(method) but without relying on jQuery. Intended Outcome //Replicates the functio ...

Fulfill all of the promises within Bluebird, as well as decline any that do

I am in search of a method to retrieve both successful resolutions and rejections from a promise array. I am relying on the Bluebird implementation, so any ES6 compatible solution would be preferable. One option that comes to mind is utilizing Bluebird&ap ...

What is the best way to implement a switch case with multiple payload types as parameters?

I am faced with the following scenario: public async handle( handler: WorkflowHandlerOption, payload: <how_to_type_it?>, ): Promise<StepResponseInterface> { switch (handler) { case WorkflowHandlerOption.JOB_APPLICATION_ACT ...

Obtaining a string from the String prototype can be achieved by using

My goal is to create a custom log method for the String object that will print out the actual string value, but I'm facing some difficulties in getting it to work correctly. String.prototype.log = function() { console.log(this.valueOf()); } &apos ...

Utilize Ramda.js to transform commands into a functional programming approach

I have written a code to convert an array of numbers into a new datalist using imperative style. However, I am looking to convert it to functional style using a JavaScript library like ramdajs. Code Background: Let's say we have 5 coins in total with ...

Does the Mirage addon work effectively in the ember.js tutorial?

Following the ember.js tutorial, I'm facing a roadblock at this particular stage: (especially when implementing the Mirage add-on). I've made changes to the mirage/config.js file as advised but still unable to display the Mirage data. Despite ...

Find the element that contains a specific substring in its value using JavaScript

I am trying to find a way to count how many input fields with the class name "text" contain a specific value. document.getElementById('c_files').getElementsByClassName('text').length; Currently, this code counts all textboxes with the ...

Elastic_Frame | "Error: Unable to process action as property 'toLowerCase' is not defined"

Attempting to create a personal and project portfolio using Vu Khanh Truong's "elastic_grid" jQuery plugin for the actual portfolio. You can access it here. However, encountering some issues on my page: 1) The header for the portfolio section disappe ...

PHP is unable to provide a JSON response

What could be causing a PHP file not to respond as JSON, while it responds correctly to the connected file? File Response Code <?php header("Access-Control-Allow-Origin: *"); header("Content-Type: application/json; charset=UTF-8"); include '.. ...

Move the JavaScript code from the <script> element in the HTML file to a

Recently, I've been exploring the idea of incorporating a tradingview ticker on my website. Trading view has kindly provided me with a snippet to embed into my webpage: <!-- TradingView Widget BEGIN --> <div class="tradingview-widget-co ...

Stop automatic form submissions from the enter key

My live chat messaging system is experiencing an issue where the page refreshes every time a user presses the enter button. I attempted to use prevent default code, but it did not work for me. I'm new to website programming, so if there are any proble ...

How to use AJAX script to call a non-static page method in ASP.NET

Is it possible to achieve this task without utilizing the UpdatePanel feature? ...

What are the steps to troubleshooting using VS Code and Chrome browser with Webpack?

Can anyone provide guidance on how to debug webpack in VS Code with the Chrome browser? As a beginner in programming, I'm struggling because webpack minifies everything into one line which makes traditional debugging methods ineffective. I haven' ...

Tips for improving the loading speed of Ajax applications

Having an issue with the speed of loading AJAX pages on my main.php and ajx_receipt_sub_detail.php. Looking for suggestions to increase the loading speed of AJAX. Main.php <script src="scripts/jquery-1.11.0.min.js"></script> <script> f ...

Issues with returning a response in AWS Lambda using NodeJs

I have been experimenting with a basic Node Js example on AWS Lambda that includes the Async library. The code seems to be functioning correctly, however, for some reason, the Lambda Function is returning a null response. As a newcomer to Node, I could use ...

The PHP script is not receiving any data when checking if the value is set in the $_POST variable

I'm attempting to transmit values from a JavaScript file using POST method to a PHP page. Here is the AJAX code: let userInput = $input.val(); $.ajax({url: "../checkout/test.php", type : 'post', data : {'userInput': user ...