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

I am trying to understand why my React component's render function is being called twice - first without any data and then again with data, resulting in a

I am facing an issue with my TreeNav component, where the data is fetched from an API call. I have set up the reducer, action, and promise correctly, but when I try to map over the data in the component render function, I get an error saying "Uncaught Type ...

Adding event listeners to elements created dynamically

I am facing an issue with some dynamically generated divs from a JavaScript plugin. The divs have a class .someclass which wraps existing divs. My goal is to add a class to the children of .someclass. I attempted to achieve this by using the following code ...

What is the best way to tidy up a function within a useEffect hook?

When updating state within a useEffect hook while using async/await syntax, I encountered an error regarding the cleanup function. I'm unsure how to properly utilize the cleanup function in this scenario. Error: Warning - A React state update was att ...

What is the best way to utilize MUI breakpoints for displaying images based on different screen sizes?

I need help displaying an image based on the screen size using MUI breakpoints. I'm struggling to understand how to implement this with MUI. Can someone assist me with the breakpoints? interface EmptyStateProps { title: string; description: string ...

I am continuously encountering PHP errors related to the values I am passing through AJAX requests

I've been struggling with AJAX lately. While I don't have any issues sending values using a form tag to a PHP file, I'm trying to enhance my program by incorporating jQuery and AJAX. However, I've hit a roadblock for the past few days. ...

Looping through nested arrays in an array of objects with Angular's ng-repeat

I'm struggling to access an array within an array of objects in my AngularJS project. Here's the HTML: <li ng-repeat="ai in main.a2"> <div np-repeat="bi in ai.b"> <span ng-bind="bi"></span>b2 </div> </l ...

Converting a string to HTML in Angular 2 with proper formatting

I'm facing a challenge that I have no clue how to tackle. My goal is to create an object similar to this: { text: "hello {param1}", param1: { text:"world", class: "bla" } } The tricky part is that I want to ...

Issue with inconsistent indentations in Pug template

Dealing with the Pug template engine has been a frustrating experience. Despite spending an entire day trying to figure it out, all I got was errors about inconsistent indentations. It's disheartening when my text ends up in the "our sponsor section" ...

Making jQuery work: Utilizing tag replacements

My current code is: this.html(this.html().replace(/<\/?([i-z]+)[^>]*>/gi, function(match, tag) { return (tag === 'p') ? match : '<p>'; return (tag === '/p') ? match : '</p& ...

What is the best way to use jQuery to refresh a partial in Ruby and insert it into a specific div element?

One of my web elements is a button that has the following appearance: <%= link_to "Join", "#", :id => "joinleave", :class => "buttonrefresh small join button expand", :'project-id' => @project.id %> Upon clicking this button, I h ...

Display loading spinner and lock the page while a request is being processed via AJAX

Currently, I am working on a project using MVC in C#, along with Bootstrap and FontAwesome. The main objective of my project is to display a spinner and disable the page while waiting for an ajax request. Up until now, I have been able to achieve this go ...

Slowly revealing sticky navigation with slideDown animation using JQuery

Here is the code for a .JS file: $(document).scroll(function (){ var menuheight= $('header').height(); var y = $(this).scrollTop(); if (y>(menuheight)) { $('.menu_nav_features').addClass ...

Is there a way to verify user credentials on the server using FeathersJS?

Currently, my single-page app is utilizing feathers client auth and a local strategy for authentication. I have implemented various middleware routes and I am looking to verify if the user is authenticated. If not, I would like to redirect them to /. Bel ...

The JSON GET method displays HTML content when accessed through code or console, but presents a JSON object when accessed through a web address

I am currently trying to execute the following code: $(document).ready(function () { $.ajax({ url: 'http://foodfetch.us/OrderApi/locations', type: 'GET', success: function(data){ alert(data); ...

What are some methods for utilizing jQuery or Javascript to dynamically modify CSS styles depending on the current URL?

I'm working on integrating a separate navigation area file with my content using PHP includes. I have this idea where I want the links in the navigation area to change color depending on the active page (current URL). Essentially, I need jQuery or Jav ...

Angular error ReferenceError: $Value is not defined in this context

As a newcomer to AngularJS, I am facing an issue while passing a list from the HTML file to the backend for processing. The error message ReferenceError: $Value is not defined keeps popping up. Within my controller file, I have a function named test. The ...

Unable to make a successful POST request using the JQuery $.ajax() function

I am currently working with the following HTML code: <select id="options" title="prd_name1" name="options" onblur="getpricefromselect(this);" onchange="getpricefromselect(this);"></select> along with an: <input type="text" id="prd_price" ...

Checking for the existence of a row in Node.js using Sqlite3

Wondering if it's possible to verify the existence of a row using node.js and the sqlite module. I currently have this function in place, but it always returns false due to the asynchronous nature of the module. function checkIfRowExists(username, pa ...

I have a json file that I need to convert to a csv format

I am currently working with a json file, but I need to switch it out for a csv file. Do I have to use a specific library to accomplish this task, or can I simply modify the jQuery 'get' request from json to csv? I attempted the latter approach, b ...

javascript send variable as a style parameter

screen_w = window.innerWidth; screen_h = window.innerHeight; I am trying to retrieve the dimensions of the window and store them in variables. Is there a way to then use these variables in my CSS styles? For example: img { width: screen_w; height: s ...