jqPlot + Asp.net: Dynamic pie chart with jQuery ajax, C#

/ / 1 Comments

jqPlot Pie Chart: This article explains how to create a Pie chart using jqPlot jQuery plugin in Asp.net c#.  .i.e We dynamically create a pie chart with the database ( MS SQL server) connectivity using jqPlot in Asp.net C#. You can also check my previous article on Charting.

What is jQplot?

jqPlot is a plotting and charting plugin for the jQuery Javascript framework. jqPlot produces beautiful line, bar and pie charts with many features. Screenshots: [caption id="attachment_2897" align="aligncenter" width="471"]Using jqPlot Asp.net c# pie chart example with database Using jqPlot Asp.net c# pie chart example with database[/caption]

Step to generate dynamic Pie Chart

  1. Create Database , .i.e table with some data.
  2. Download jqPlot and jQuery latest library.
  3.  Html Markup: add a `Div` tag where pie chart will display.
  4.  Server-side C#- Create a WebService ( WebMethod) which returns data.
  5. Client side jQuery - code to initialize jqPlot and binding data to it.

# Create Database:

Here in our database, we have a `Table` as tb_city_population, and `column` as City Name and Population.

We are going to create pie chart dynamically, which displays population percentage for respected cities from our database ( MS SQL server ).

Table Schema ScreenShot:

Fig 1Database design schemna used to build pie chart using jqPlot Asp.net c#  

Now add some data into our table check Fig 2.

Fig 2 Database - add data to our table which is used to build pie chart using jqPlot Asp.net c#  

# Download jqPlot and jQuery files.

Now download and include jqPlot and jQuery file. You can host the jQuery file on your server, or you can also use from the Google-hosted site.

So now our head tag looks like as written below.

//*
<link href="Scripts/jqPlot/jquery.jqplot.min.css" rel="stylesheet" />
<script src="latestJs_1.11/jquery.min.js"></script>
<script src="Scripts/jqPlot/jquery.jqplot.min.js"></script>
<script src="Scripts/jqPlot/jqplot.pieRenderer.min.js"></script>
//*


# HTML Markup :

Here we add a `drop-down` list, `div` tag and a `button`.  On Button tag we bind `click` event which makes an ajax call, Div tag is used to display Pie Chart.

Finally, this is how our HTML looks like as written below

<div>
    Select Year :
    <select id="ddlyear">
        <option>2010</option>
        <option>2011</option>
        <option>2012</option>
        <option>2013</option>
        <option>2014</option>
        <option>2015</option>
    </select>
    <button id="btnCreatePieChart">Create Pie chart</button><br />
    <div id="chartdiv" style="height: 350px; width: 500px;"></div>
</div>

# Code Behind: Create a WebMethod, which returns JSON data and its use to create Pie Chart dynamically.

First, we add a WebService file (ASMX file ) in our Asp.net Web Application. Now we create a class as cityPopulation in our `asmx` file as shown below.

//*
public class cityPopulation 
{
   public string city_name { get; set; }
   public int population { get; set; }
   public string id { get; set; }
}
//*

Now write a WebMethod in our ASMX file, which returns the list of city name with city population count, and on the client side, we bind this data to our div using jqPlot to generate Pie Chart.

I must suggest you have a look at Simple jQuery Ajax JSON Example in Asp.net with SQL database.

Our C# WebMethod code looks like as shown below.

[WebMethod]
 public List<cityPopulation> getCityPopulation(List<string> pData)
 {
        List<cityPopulation> p = new List<cityPopulation>();

   using (SqlConnection cn = new SqlConnection(conn))
   {
     string myQuery = "SELECT id_, city_name, population FROM  tb_city_population WHERE  year_of = @year";
      SqlCommand cmd = new SqlCommand();
      cmd.CommandText = myQuery;
      cmd.CommandType = CommandType.Text;
      cmd.Parameters.AddWithValue("@year", pData[0]);
      cmd.Connection = cn;
      cn.Open();
      SqlDataReader dr = cmd.ExecuteReader();
     if (dr.HasRows)
     {                
         while (dr.Read())
         {
          cityPopulation cpData = new cityPopulation();
          cpData.city_name = dr["city_name"].ToString();
          cpData.population =Convert.ToInt32(dr["population"].ToString());
          p.Add(cpData);
         }
     }
   }
     return p;
 }

 # jQuery code to initialize jqPlot and display Pie Chart.

We are done with our server-side code now its time to work on client side. Using jQuery will call an ajax method and on its success response, we bind `JSON` data to generate pie chart using `jqPlot Plugin` with dynamic data.

Our jQuery code looks like as shown below.

$("#btnCreatePieChart").on('click', function (e) {

    var self = $(this);
    var pData = [];
    pData[0] = $("#ddlyear").val();

    var jsonData = JSON.stringify({ pData: pData });

    $.ajax({
        type: "POST",
        url: "WebService.asmx/getCityPopulation",
        data: jsonData,
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        success: OnSuccess_,
        error: OnErrorCall_
    });

    function OnSuccess_(response) {
        var aData = response.d;
        var arr = []

        $.map(aData, function (item, index) {
            var i = [item.city_name, item.population];
            arr.push(i);
        });
              
        var plot1 = jQuery.jqplot('chartdiv', [arr],
            {
                seriesDefaults: {
                    // Make this a pie chart.
                    renderer: jQuery.jqplot.PieRenderer,
                    rendererOptions: {
                        // Put data labels on the pie slices.
                        // By default, labels show the percentage of the slice.
                        showDataLabels: true
                    }
                },
                legend: { show: true, location: 'e' }
            }
        );

    }
    function OnErrorCall_(response) {
        alert("Whoops something went wrong!");
    }
    e.preventDefault();
});

Output:

We are done,  this is how our Pie chart looks. Using jqPlot Asp.net c# pie chart example with database  

You can also check these articles:

  1. Chart.js Asp.net: Create Pie Chart with database Jquery Ajax C#.
  2. Chart.js Asp.net: Create Line chart with database Jquery Ajax C#.
  3. Generic Handler ashx file: Post send JSON data in Asp.net C#.
  4. jQuery Ajax JSON Example in Asp.net with SQL database.

Thank you for reading, pls keep visiting this blog and share this in your network. Also, I would love to hear your opinions down in the comments.

PS: If you found this content valuable and want to thank me? 👳 Buy Me a Coffee

Subscribe to our newsletter

Get the latest and greatest from Codepedia delivered straight to your inbox.


Post Comment

Your email address will not be published. Required fields are marked *

1 Comments

  1. Rocky dave 06/03/2015 17:52:55
    Hi , thanks for such nice post, i was looking for this only to create dynamic ppie chart using jqPlot with asp.net , and there are many tuts with PHP , good to find in asp.net too thanks again, keep the good work :-)