Refreshing chart when load data into a grid

Hello, I have a problem with refreshing a chart inside a layout cell when I load new data into a grid , or when I filter data. The grid is inside the other cell of layout.

Console error is

TypeError: barChart is undefined

my code is

<!DOCTYPE html>
<html>
<head>
   <title>LIMS Istituto Zooprofilattico Sperimentale - Apparecchiature</title>
   <meta charset="utf-8">
   <script src="codebase/dhtmlx.js" type="text/javascript"></script>
   <link rel="stylesheet" type="text/css" href="codebase/dhtmlx.css">
   <style>
         html, body {
            width: 100%;      /*provides the correct work of a full-screen layout*/ 
            height: 100%;     /*provides the correct work of a full-screen layout*/
            overflow: hidden; /*hides the default body's space*/
            margin: 0px;      /*hides the body's scrolls*/
         }
   </style>
      
   </head>
            
      <script type="text/javascript">

         var barChart;
      

         function doOnLoad() {
            
            myLayout = new dhtmlXLayoutObject(document.getElementById("layoutObj"),"2U"); 

            myToolbar = myLayout.attachToolbar();
            myToolbar.loadStruct("data/toolbar.xml");

...
...
            
            myGrid = myLayout.cells("a").attachGrid();
				...
				...
            myGrid.init();
            myGrid.load("data/apparecchiature.php",refresh_chart);
               
            // Eventi Grid //
            myGrid.attachEvent("onEditCell",function(stage){   //netsam
               if (stage == 2)
                  refresh_chart();
                  return true;
            });

            // Eventi Toolbar //
            myToolbar.attachEvent("onclick",function(id){
               };
               if(id=="delContact"){
               }
               if(id=="statContact"){
                  showView("chart");
               }
               if(id=="formContact"){
                  showView("def");
               }
            
            });

         } //fine onLoad
         
         
         
 
         function refresh_chart(){
            barChart.clearAll();
            barChart.parse(myGrid,"dhtmlxgrid");
         };


      </script>

   </head>


   
   <body onload="doOnLoad();">
         
      <header>
      <hgroup>
          <img class="middle piccola" src="img/logo.gif" alt="Logo Istituto Zooprofilattico Sicilia">
          <span><h2>Istituto Zooprofilattico Sperimentale della Sicilia "A. Mirri"</h2></span>
          <span class="destra"><h3>Laboratory Information Management System</h3></span>
          <span class="destra beige"><h2>LIMS</h2></span>
      </hgroup>
      </header>

      <div id="layoutObj">
      </div>
      <!--      
      <footer>
         <small>©2014 Realizzato da Ignazio Sammarco, Maurizio Orlando, Giuseppe Lo Bue, Daniele Montemaggiore, Sergio Caramanno. </small>
      </footer>
      -->

   </body>
   
</html>

Thank you to all for the help

Could you clarify where is the init of your barChart?

Yes

<script type="text/javascript">

      var barChart;

      function doOnLoad() {
         ...
            myToolbar.attachEvent("onclick",function(id){
               ...
               if(id=="statContact"){
                  showView("chart");
              }
      }

      function showView(view) {
         ...
         if (view == "chart") {
                 ...  
                 barChart = myLayout.cells("b").attachChart(chartConfig);
                 barChart.parse(myGrid,"dhtmlxgrid");
                 ...
         }
      }


      function refresh_chart(){
            barChart.clearAll();
            barChart.parse(myGrid,"dhtmlxgrid");
      }


so you are initing your chart on clicking on the toolbar button.
but you call the refresh_chart function right when the data is loaded to the grid.
Is the toolbar button clicked at that moment?

Yes because I want to show the chart only when I click on toolbar button

Because I thought that if I filter a grid the data are loaded again, or not? Do I have to load it? and how ?

I don’t understand. Sorry!!

Initially I have a grid on left, a form on right. When I click toolbar button I change view on right with the graph.

Another thing I SOLVED is: When I filter the data and click another time toolbar button the graph refresh. Before didn’t change because I wrote:

         function showView(view) {
         
            var firstShow = myLayout.cells("b").showView(view);
            
            // view became visible first time, loading content
            if (firstShow) {
            
               if (view == "chart") {
                   barChart = myLayout.cells("b").attachChart(chartConfig);
                   barChart.parse(myGrid,"dhtmlxgrid");

Then I cancel " if (firstShow) { " statement and when I click toolbar the chart refresh.

I attach my entire index.html file. Is the unique javascript file I use.

<!DOCTYPE html>
<html>
<head>
   <title>LIMS Istituto Zooprofilattico Sperimentale - Apparecchiature</title>
   <meta charset="utf-8">
   <script src="codebase/dhtmlx.js" type="text/javascript"></script>
   <link rel="stylesheet" type="text/css" href="codebase/dhtmlx.css">
   <style>
         html, body {
            width: 100%;      /*provides the correct work of a full-screen layout*/ 
            height: 100%;     /*provides the correct work of a full-screen layout*/
            overflow: hidden; /*hides the default body's space*/
            margin: 0px;      /*hides the body's scrolls*/
         }
      
         header{
            height: 10%;
            background: #000055;
            color: #fff;
            overflow: hidden; /*hides the default body's space*/
            /*display: table-cell; 
            vertical-align: middle;*/
            line-height:20px; /*serve per l'allineamento verticale*/
         }
         div#layoutObj{
            height: 85%;
         }
         footer{
            height: 4%;
         }
         
         /* vertically align text */ 
         span { 
            display:inline-block; 
            vertical-align:middle 
         }
         img.piccola{
            height: 50px;
         }
         img.middle {
            vertical-align:middle;
         }
         .destra{
            float: right;
            margin-right: 20px;
         }
         .beige{
            color: #ffebcd; 
         }
         
         /* Grafici - Chart Dhtmlx */
         .dhx_axis_item_x{
            font-size: 11px
         }
         .dhx_axis_item_y{
            font-size: 11px
         }
                  
         /*personalizzazione css -> Non documentata*/   
         .dhxform_base {
            position: relative;
            margin: 10px;
            padding: 15px 30px 17px;
            border: 1px solid #cecece;
         }
         
   </style>
      
   </head>
      
      <!-- Script principale -->
      
      <script type="text/javascript">

         var barChart;
         var myGrid;
         var myLayout;   
         var myMenu;
         var myToolbar;
         
         var grid_header       = "Sic,Descrizione bene,Costruttore,Reparto stanza,Ord";
         var grid_column       = "sic,descrizione_bene,costruttore,reparto_stanza,ord";
         var grid_sorting       = "str,str,str,str,int";
         var grid_coltype       = "ro,ro,ro,ro,ed";
         var grid_colWidths    = "100,300,100,200,*";
         var grid_colAlign    = "left,left,left,left,right";
         var grid_filter      = "#text_filter,#text_filter,#text_filter,#text_filter";
         
         dhtmlx.image_path = "codebase/imgs/";

      

         function doOnLoad() {
            
            //myLayout = new dhtmlXLayoutObject({parent: "layoutObj", pattern: "3L"});
            //var layout = new dhtmlXLayoutObject("layoutObj","2U");
            //var layout = new dhtmlXLayoutObject(document.body,"2U"); 
            myLayout = new dhtmlXLayoutObject(document.getElementById("layoutObj"),"2U"); 
            myLayout.cells("a").setText("Apparecchiature");       
            myLayout.cells("b").setText("Dettaglio apparecchiatura");
            myLayout.cells("b").setWidth(580);
            //layout.xy.margin_top = 150;//height of menu
               
            //var menu = layout.attachMenu();
            //menu.setIconsPath("icons/");
            //menu.loadStruct("data/menu.xml");
         
            // by the default "def" view used, when layout is loaded
            // this view also loaded, so just init

            myToolbar = myLayout.attachToolbar();
            myToolbar.setIconsPath("icons/");
            myToolbar.loadStruct("data/toolbar.xml");

            
            myGrid = myLayout.cells("a").attachGrid();
            //myGrid.loadXML("../common/grid.xml?etc="+new Date().getTime());
            myGrid.setImagePath('codebase/imgs/');
            myGrid.setSkin("dhx_skyblue")
            myGrid.enableSmartRendering(true);
            myGrid.setHeader(grid_header);
            //sets the columns' ids
            myGrid.setColumnIds(grid_column);
            //sets the initial widths of columns      
            myGrid.setInitWidths(grid_colWidths);
            //sets the alignment of columns   
            myGrid.setColAlign(grid_colAlign);
            //sets the types of columns   
            myGrid.setColTypes(grid_coltype);
            //sets the sorting types of columns            
            myGrid.setColSorting(grid_sorting);     
            //the method takes the columns' filters as a parameter
            myGrid.attachHeader(grid_filter);
            myGrid.setStyle(
               "", "border:1px solid #5F9EA0;","", "" //background-color:#FFFFA8; color:red;
            );
				//Con smart rendering non si visualizzano alcune righe (andando veloce con Pag giu o su non si caricano lo stesso)
				myGrid.setAwaitedRowHeight(25);
				
            //hide the first column
            //mygrid.setColumnHidden(3,true);
            myGrid.init();
            //mygrid.loadXML("gridH.xml",refresh_chart);
            //myGrid.load("data/apparecchiature.php",refresh_chart);
            myGrid.load("data/apparecchiature.php",refresh_chart);

            
            contactForm = myLayout.cells("b").attachForm();
            //contactForm.loadStruct("data/form.xml");
            contactForm.loadStruct("data/form.xml", function(){
               //Aggiunge l'immagine al container - form
               //contactForm.getContainer("foto").innerHTML = '<img src="data/foto_apparecchiature/'+ "1384.png"+'">';
            });
            contactForm.bind(myGrid);   //lega il form alla griglia

            
            //Inits dataProcessor
            var dpg = new dataProcessor("data/apparecchiature.php");         
            //associates the dataProcessor instance with the grid
            dpg.init(myGrid);   

            
                        
            // Eventi Grid //
            myGrid.attachEvent("onEditCell",function(stage){   //netsam
               if (stage == 2)
                  refresh_chart();
                  return true;
            });
            myGrid.attachEvent("onRowSelect", function(id){
                  //Modifica l'immagine del container - form
                  //contactForm.setItemValue("foto", id);
				  var cellObj = myGrid.cellByIndex(id,0);
				  var image_name = cellObj.getValue();
                  var foto = "img/foto_apparecchiature/"+image_name+".jpg";
                  contactForm.getContainer("foto").innerHTML = '<img src="'+foto+'" width="200px">';
            });
            dpg.attachEvent("onAfterUpdate", function(sid, action, tid, tag){    
               if (action == "inserted"){
                  //selects the newly-created row            
                  myGrid.selectRowById(tid);
                  //set focus to the 1st form's input      
                  contactForm.setFocusOnFirstActive();                                  
               }
            });

            
            // Eventi Form //
            contactForm.attachEvent("onButtonClick", function(name, command){
               //sends the values of the updated row to the server
               contactForm.save();     
            });
            
            
            // Eventi Toolbar //
            myToolbar.attachEvent("onclick",function(id){
               // inserire indice e chiave database
               //'newContact' is the id of the button in the toolbar
               if(id=="newContact"){
                  //generates an unique id         
                  var rowId=myGrid.uid();
                  //gets the number of rows in grid            
                  var pos = myGrid.getRowsNum();     
                  //contactsGrid.addRow(rowId,["Nuovo contato","",""],pos);  //adds a new row
                  //netsam   
                  //adds a new row
                  myGrid.addRow(rowId,["Nuovo contatto","",""],0);  
                  contactForm.setItemFocus('descrizione_bene');
                  //netsam      
               };
               if(id=="delContact"){
                  var rowId = myGrid.getSelectedRowId();        
                  var rowIndex = myGrid.getRowIndex(rowId);        
                  if(rowId!=null){            
                     myGrid.deleteRow(rowId);                
                     if(rowIndex!=(myGrid.getRowsNum()-1)){                    
                        myGrid.selectRow(rowIndex+1,true);                
                     } else{                    
                        myGrid.selectRow(rowIndex-1,true)                
                     }        
                  }    
               }
               if(id=="statContact"){
                  showView("chart");
                  //var chart = layout.cells("b").attachChart(chartConfig);
                  //chart.load("sales.xml");
                  //chart.parse(contactsGrid,"dhtmlxgrid");
                  //alert(barChart);
               }
               if(id=="formContact"){
                  showView("def");
               }
            
            });

         } //fine onLoad
         
         
         
         
         function showView(view) {
         
            var firstShow = myLayout.cells("b").showView(view);
            
            // view became visible first time, loading content
            //if (firstShow) {
            
               if (view == "chart") {

						myLayout.cells("b").setText("Numero di apparecchiature per reparto");
                  // Inits Chart config //
                  var chartConfig ={
                     view: "bar",
                     color:"#66ccff",
                     gradient:"3d",
                     //container:"chart_container",
                     //container:layout.cells("b"),
							
							//value:"#count#",
                     value:"#data4#",   //Valori relativi al Reparto
							
                     label:"#data4#",
							
                     tooltip:{
                        template:"#id#" //categoria raggruppata
                     },
                     group:{
                        by:"#data3#", //Reparto
                        map:{
								
									data4:[null,getCount]
                           //data4:["#data4#","sum"]
                        }
                     },
							xAxis : {
									lines: false,
									template: "",
									//template: "#id#",
									/*
									template:function(obj, common, data){
										if (obj.id%2) return obj.id;
										return "";
									},
									*/
									title: "Reparti"
							}
                  }
                  
                  barChart = myLayout.cells("b").attachChart(chartConfig);
                  barChart.parse(myGrid,"dhtmlxgrid");
                  //barChart.setImagePath("../../../codebase/imgs/dhxtree_skyblue/");
                  //barChart.loadXML("../common/tree.xml?etc="+new Date().getTime());
                  
               }
               
               if (view == "form") {
                  //myLayout.cells("b").attachURL("../../../dhtmlxWindows/samples/common/test_page_1.html", true);
                  contactForm = myLayout.cells("b").attachForm();
                  //contactForm.loadStruct("data/form.xml");
                  contactForm.loadStruct("data/form.xml", function(){
                     //Aggiunge l'immagine al container - form
                     //contactForm.getContainer("foto").innerHTML = '<img src="data/foto_apparecchiature/'+ "1384.png"+'">';
                  });
                  contactForm.bind(myGrid);   //lega il form alla griglia
               }

            //}
         }

            
         //---------------
         // Funzioni varie
         //---------------

         function doLink(name, value) {
            if (name == "product") return "<div class='simple_bold'>"+value+"</div>";
            if (name == "libretto") return "<div class='simple_link'><a href='"+"libretti/"+value+".pdf"+"'target='blank'>"+value+"</a></div>";
            //if (name == "pgs") return "<div class='simple_link'><a href='http://"+value+"'target='blank'>"+value+"</a></div>";
            //if (name == "pos") return "<div class='simple_link'><a href='http://"+value+"'target='blank'>"+value+"</a></div>";            
         };

         function refresh_chart(){
            barChart.clearAll();
            barChart.parse(myGrid,"dhtmlxgrid");
         };
			
			function getCount(prop,data){
				var count = data.length;
				return count;
         };

			
      </script>

   </head>


   
   <body onload="doOnLoad();">
         
      <header>
      <hgroup>
          <img class="middle piccola" src="img/logo.gif" alt="Logo Istituto Zooprofilattico Sicilia">
          <span><h2>Istituto Zooprofilattico Sperimentale della Sicilia "A. Mirri"</h2></span>
          <span class="destra"><h3>Laboratory Information Management System</h3></span>
          <span class="destra beige"><h2>LIMS</h2></span>
      </hgroup>
      </header>

      <div id="layoutObj">
      </div>
      <!--      
      <footer>
         <small>©2014 Realizzato da Ignazio Sammarco, Maurizio Orlando, Giuseppe Lo Bue, Daniele Montemaggiore, Sergio Caramanno. </small>
      </footer>
      -->

   </body>
   
</html>

I can subtitute this line:

            //myGrid.load("data/apparecchiature.php",refresh_chart);
            myGrid.load("data/apparecchiature.php");

So I don’t call refresh_chart before initializing my chart. The error disappears. But how can I automatic refresh my chart without clicking the toolbar button??

If you are calling:
myGrid.load(“data/apparecchiature.php”,refresh_chart);
your refresh_chart function will be called once when the data is loaded to the grid.

If you need to refresh your chart after the the grid filtering you may use the onFilterEnd event.
For example:
myGrid.attachEvent(“onFilterEnd”, refresh_chart);

thanks, it works.