How to Create Charts Dynamically Using jQuery

Introduction

In one of my previous articles I explained how to Create Pie Chart Using jQuery, but that chart was not dynamic, it was a completely static chart where the data was provided statically, the chart was created statically. If you would have tried to create the chart using that article then you would have encountered many problems creating a new chart on a click of a button.

In this article I'll tell you about How to Create Charts (Google Charts) Dynamically.

Here all the things will be dynamic, the data will be fetched from a database, single code will be written for all the charts you want to make, so using this article your reusability and maintainability of code will be much improved.

I will create charts for various states and their cities, in other words charts of cities by state will be created.

Step 1

First of all I created two tables, one for the states and another for cities.

Dynamic Charts

In the City table StatesID is taken as a foreign key and that means we will work around the ID of the States. I have provided some dummy data in both of the tables (you can create your own tables).

Now our database is done and we can move towards the code.

Step 2

Now I am creating a table where the state's name will be provided on buttons of each row. Here I am providing the ID to each button and I'll use these IDs as StateID of the State table, you can fetch State tables data and can bind output to the table so in that way your state's name and their ID will be dynamic (if any one of you want code to fetch State table data and bind to a HTML table then you can ask me for that in the comments section).

  1. <body>  
  2.     <form id="form1" runat="server">  
  3.         <table id="chartTable">  
  4.             <tr>  
  5.                 <td>  
  6.                     <input type="button" id="1" class="callChart" value="Delhi" />  
  7.                 </td>  
  8.             </tr>  
  9.             <tr>  
  10.                 <td>  
  11.                     <input type="button" id="2" class="callChart" value="Uttar Pradesh" />  
  12.                 </td>  
  13.             </tr>  
  14.             <tr>  
  15.                 <td>  
  16.                     <input type="button" id="3" class="callChart" value="Bihar" />  
  17.                 </td>  
  18.             </tr>  
  19.             <tr>  
  20.                 <td>  
  21.                     <input type="button" id="4" class="callChart" value="Maharashtra" />  
  22.                 </td>  
  23.             </tr>  
  24.         </table>  
  25.     <div id="piechart">  
  26.       
  27.     </div>  
  28.         <input type="hidden" id="hdn1" />  
  29.     </form>  
  30. </body> 

Step 3

Now I will write the jQuery code.

First of all add a reference for jQuery and Google Charts in the head section of your page like this:

  1. <head runat="server">    
  2.     <title></title>    
  3.    <script type="text/javascript" src="https://www.google.com/jsapi"></script>    
  4.     <script src="jquery-1.7.1.js"></script>    
  5. </head> 

Google Charts is the first thing to initialize while the paging is loading, so if you are trying to initialize them after the page load then it'll be of no use and if you can initialize them when you want then please let me know so that I can improve my code and my knowledge.

As I have said, Google Charts is the first thing to initialize so don't write the initialization code under any $(document).ready() or anything else, place the charts code in a separate Script section. That would be very beneficial for you. Write this code in the Script section for the initialization:

  1. function initialize() 
  2. {  
  3.     $('.callChart').live('click'function () 
  4. {  
  5.         drawChart();  
  6.     });  
  7. };  
  8.    google.load("visualization""1", { packages: ["corechart"] });  
  9.    google.setOnLoadCallback(initialize); 

callChart is a class name provided to all the buttons, this means that the drawChart() function would be called on the click of each button having the callChart class.

Step 4

Now I am creating another Script tag and in this tag I will call the click event of these buttons:

  1. <script>  
  2.     $(function () {  
  3.         $("#chartTable input").click(function () {  
  4.             $('#hdn1').val($(this).attr('id'));  
  5.         });  
  6.     });  
  7. </script> 

On the click function I have passed the button ID into a hidden variable because we need it in future code.

Step 5

Now return to the first script tag where the charts code was written and create the drawChart() function as in the following:

  1. function drawChart() {  
  2.     var stateName = $('#hdn1').val();  
  3.     jQuery.ajax({  
  4.         type: 'POST',  
  5.         contentType: "application/json; charset=utf-8",  
  6.         url: 'WebService1.asmx/getCityData',  
  7.         data: "{'stateName':'" + stateName + "'}",  
  8.         dataType: 'JSON',  
  9.         success: function (response) {  
  10.             StateCityChart(response);  
  11.             return false;  
  12.         },  
  13.         error: function (er, sw, sq) { 
  14.             //alert("Error occured in application");  
  15.         }  
  16.     });  

Here I am fetching the value from a hidden field and passing it to the variable. After this an AJAX call is made to a Web Service where the method named getCityData is called so let's see what I have done there.

Step 6

I have created a Web Service in which a web method is created named getCityData and it's code is as follows:

  1. [WebMethod(EnableSession = true)]  
  2. public List<CityData> getCityData(string stateName)  
  3. {  
  4.     DataTable dt = new DataTable();  
  5.     List<CityData> list = new List<CityData>();  
  6.     CityData citydata;  
  7.     try  
  8.     {  
  9.         string connStr = ConfigurationManager.ConnectionStrings["myConnectionString"].ConnectionString;  
  10.         SqlConnection con = new SqlConnection(connStr);  
  11.         con.Open();  
  12.         var query = "SP_getCityData";  
  13.         SqlCommand com = new SqlCommand(query, con); //creating SqlCommand object  
  14.         com.CommandType = CommandType.StoredProcedure;  
  15.         com.Parameters.AddWithValue("@stateName ", stateName);  
  16.         com.ExecuteNonQuery();  
  17.         con.Close();  
  18.         SqlDataAdapter adptr = new SqlDataAdapter(com);  
  19.         adptr.Fill(dt);  
  20.         citydata = new CityData(dt);  
  21.         list.Add(citydata);  
  22.     }  
  23.     catch (Exception ex)  
  24.     {  
  25.     }  
  26.     return list;  
  27. }  
  28. public class CityData  
  29. {  
  30.     public CityData(DataTable dt)  
  31.     {  
  32.         string statecityData = JsonConvert.SerializeObject(dt);  
  33.         this.CityGridData = statecityData;  
  34.     }  
  35.     private string _cityGridData;  
  36.     public string CityGridData  
  37.     {  
  38.         get { return _cityGridData; }  
  39.         set { _cityGridData = value; }  
  40.     }  
  41. }

In this web method I called a Stored Procedure named "SP_getCityData".

  1. create proc SP_getCityData  
  2. ( @stateName int)  
  3. as  
  4. begin  
  5. select CityName, RegisteredUsers from Cities  
  6. where StateID=@stateName  
  7. end 

This procedure takes the ID of a State and according to this StateID "CityID and Number of Registered Users" are fetched. This data is inserted into a Data Table, but jQuery will find it difficult to understand the Data Table so we need to send the data in List format.

This data is serialized in JSON format using JsonConvert.SerializeObject(), this serialization is done in a class named CityData. I had sent the serialized data into the list and then I had returned it.

Step 7

This list is returned to the success function. In the success function list it is transferred to another function named StateCityChart();

The code of the StateCityChart function is as follows:

  1. function StateCityChart(response) {  
  2.     response.d = JSON.parse(response.d[0].CityGridData);  
  3.     var list = response.d;  
  4.     var dataArray = [['City''Value']];  
  5.     $.each(list, function (index, table) {  
  6.         dataArray.push([table.CityName, table.RegisteredUsers]);  
  7.     });  
  8.     var data = google.visualization.arrayToDataTable(dataArray);  
  9.     var options = {  
  10.         title: 'State wise cities chart',  
  11.         sliceVisibilityThreshold: 0  
  12.     };  
  13.     var chart = new google.visualization.PieChart(document.getElementById('piechart'));  
  14.     chart.draw(data, options);  
  15.     return false;  
  16. };

Here I had parsed the serialized list and transferred all the data into an array. This array will be used to create the chart. When you want to create the chart using an array you need to use google.visualization.arrayToDataTable();.

After this I had provided the title of charts.

sliceVisibilityThreshold: 0 is used to show the data even if they are carrying a "0" value. Google Charts don't show least values in case your data has a high range to show so for those cases you need to write sliceVisibilityThreshold: 0 so that all the data can be shown in the chart.

You need to pass the ID of div where the charts would be created, in my case this ID is "piechart" and I had passed it in the ending lines of code.

At the end pass your array and chart option chart.draw(), chart.draw() is the function that will create the charts for us.

Output

Now all the work is done and our code is ready to be executed. Run the application to see the output.

Dynamic Charts

First of all, all the buttons will be available on the click of which chart will be created.

On click of each button the chart data will be changed.

Dynamic Charts


Dynamic Charts

The complete code of this application is as follows.
 
jQuery Code
  1. <head runat="server">  
  2.     <title></title>  
  3.     <script type="text/javascript" src="https://www.google.com/jsapi"></script>  
  4.     <script src="jquery-1.7.1.js"></script>  
  5.     <script>  
  6.         function drawChart() {  
  7.             var stateName = $('#hdn1').val();  
  8.             jQuery.ajax({  
  9.                 type: 'POST',  
  10.                 contentType: "application/json; charset=utf-8",  
  11.                 url: 'WebService1.asmx/getCityData',  
  12.                 data: "{'stateName':'" + stateName + "'}",  
  13.                 dataType: 'JSON',  
  14.                 success: function (response) {  
  15.                     StateCityChart(response);  
  16.                     return false;  
  17.                 },  
  18.                 error: function (er, sw, sq) {  
  19.                     debugger;  
  20.                     //alert("Error occured in application");  
  21.                 }  
  22.             });  
  23.         }  
  24.    
  25.         function initialize() {  
  26.             $('.callChart').live('click'function () {  
  27.                 drawChart();  
  28.             });  
  29.         };  
  30.    
  31.    
  32.         function StateCityChart(response) {  
  33.             response.d = JSON.parse(response.d[0].CityGridData);  
  34.             var list = response.d;  
  35.             var dataArray = [['City''Value']];  
  36.             $.each(list, function (index, table) {  
  37.                 dataArray.push([table.CityName, table.RegisteredUsers]);  
  38.             });  
  39.             var data = google.visualization.arrayToDataTable(dataArray);  
  40.             var options = {  
  41.                 title: 'State wise cities chart',  
  42.                 sliceVisibilityThreshold: 0  
  43.             };  
  44.             var chart = new google.visualization.PieChart(document.getElementById('piechart'));  
  45.             chart.draw(data, options);  
  46.             return false;  
  47.         };  
  48.   
  49.         google.load("visualization""1", { packages: ["corechart"] });  
  50.         google.setOnLoadCallback(initialize);  
  51.   
  52.     </script>  
  53.     <script>  
  54.         $(function () {  
  55.             $("#chartTable input").click(function () {  
  56.                 $('#hdn1').val($(this).attr('id'));  
  57.             });  
  58.         });  
  59.     </script>  
  60. </head> 
 WebService Code
  1. [System.Web.Script.Services.ScriptService]  
  2.   public class WebService1 : System.Web.Services.WebService  
  3.   {  
  4.       [WebMethod]  
  5.       public string HelloWorld()  
  6.       {  
  7.           return "Hello World";  
  8.       }  
  9.       [WebMethod(EnableSession = true)]  
  10.       public List<CityData> getCityData(string stateName)  
  11.       {  
  12.           DataTable dt = new DataTable();  
  13.           List<CityData> list = new List<CityData>();  
  14.           CityData citydata;  
  15.           try  
  16.           {  
  17.               string connStr = ConfigurationManager.ConnectionStrings["myConnectionString"].ConnectionString;  
  18.               SqlConnection con = new SqlConnection(connStr);  
  19.               con.Open();  
  20.               var query = "SP_getCityData";  
  21.               SqlCommand com = new SqlCommand(query, con); //creating SqlCommand object  
  22.               com.CommandType = CommandType.StoredProcedure;  
  23.               com.Parameters.AddWithValue("@stateName ", stateName);  
  24.               com.ExecuteNonQuery();  
  25.               con.Close();  
  26.               SqlDataAdapter adptr = new SqlDataAdapter(com);  
  27.               adptr.Fill(dt);  
  28.               citydata = new CityData(dt);  
  29.               list.Add(citydata);  
  30.           }  
  31.           catch (Exception ex)  
  32.           {  
  33.           }  
  34.           return list;  
  35.       }  
  36.       public class CityData  
  37.       {  
  38.           public CityData(DataTable dt)  
  39.           {  
  40.               string statecityData = JsonConvert.SerializeObject(dt);  
  41.               this.CityGridData = statecityData;  
  42.           }  
  43.           private string _cityGridData;  
  44.           public string CityGridData  
  45.           {  
  46.               get { return _cityGridData; }  
  47.               set { _cityGridData = value; }  
  48.           }  
  49.       }  
  50.   } 
You can also download the source code present at the top of this article.

Up Next
    Ebook Download
    View all
    Learn
    View all