Google Visualization AddListener Example


In this blog post, we will see how to create an event for Google Visualization Datatable, and do some action based on the event. To be more specific, we will try to invoke a JSP file by passing some parameters from the row that we selected from our table. This can be opened as a Pop Up Window and can also be used with other file types like PHP etc.

The javascript part for pop up example code is provided below:
<script type="text/javascript">
function popupexample() {
var data = new google.visualization.DataTable();
data.addColumn('string', 'Name');
data.addColumn('string', 'Place');
data.addRows(2);
data.setCell(0, 0, 'John');
data.setCell(1, 0, 'Sam');
data.setCell(0, 1, 'Texas');
data.setCell(1, 1, 'California');   
visualization = new google.visualization.Table(document.getElementById('table'));
visualization.draw(data, null);
google.visualization.events.addListener(visualization, 'select',function(){
  var selection = visualization.getSelection();  
  var valueselected="get_info.jsp?name=" + data.getFormattedValue(selection[0].row, 0);  
  window.open(valueselected); 
});
}
google.setOnLoadCallback(popupexample);
</script>

After drawing the table using visualization.draw, we have added an event for the table. This event is added using the addListener method of google.visualization.events class. We pass the visualization object and identify this event of type "select". When this event gets triggered the code block inside the function() part of addListener method will get invoked.
google.visualization.events.addListener(visualization, 'select',function(){
  var selection = visualization.getSelection();  
  var valueselected="get_info.jsp?name=" + data.getFormattedValue(selection[0].row, 0);  
  window.open(valueselected); 
});

Now, this function uses getFormattedValue method of google.visualization.DataTable to get the value that was selected and passes this value to a JSP program get_info.jsp.  getFormattedValue in turns depends on visualization.getSelection() to identify which row was actually selected by the user. It is to be noted that once you get into the listener function, you can do anything that you want here, as long as you have scope for the relevant objects. The window.open event would result in a new window being opened, which could possibly be blocked by popup blockers (if installed). You can also trigger an XMLHTTPRequest inside this function and get the required data you want to display in Ajax fashion.

No comments:

Post a Comment