Click here to check my latest exciting videos on youtube
Search Mallstuffs

Flag Counter
Spirituality, Knowledge and Entertainment

Locations of visitors to this page

Latest Articles

Move to top
Calling web service asynchronously using jquery ajax
Posted By Sarin on Sep 17, 2012     RSS Feeds     Latest Hinduism news

In this article, we will see how to get data from database using jquery ajax asynchronously. We will also see how to show the data retrieved from the database onto the web page using Json
Since we are going to use Json, it is very important to have a brief knowledge of json.

What is JSON format?
JSON is a lightweight data-interchange format. Like XML, it is platform independent, easily readable and can be implemented easily in any application. Technically, JSON forms a subset of JavaScript object literal. Data stored in json format is parsed very easily and quickly by JavaScript application and hence becomes the best choice for asynchronous based web requests  
Let us directly start with the example to get a better idea.
  1)    First I will add a class with various properties which would be used for displaying data on front end side. My class would look like
public class DataModel
    public string EmailId
    public string Name
    public string Gender
    public int Salary
 I would be displaying four values (Email Id, name , gender, salary) on the front end side.
  2)    Let us now add a web service where we would make database call to retrieve data. For this example, I have created dummy data without making actual database call. My web service code would look like
[WebService(Namespace = "")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
// To allow this Web Service to be called from script, using ASP.NET AJAX, uncomment the following line.
public class DBCall : System.Web.Services.WebService
    public List<DataModel> GetData(string Gender)
        List<DataModel> data = new List<DataModel>();
        data.Add(new DataModel()  {EmailId = "[email protected]", Name = "sarin", Gender = "Male", Salary = 60000 });
        data.Add(new DataModel()  {EmailId = "[email protected]", Name = "sachin", Gender = "Male", Salary = 800000 });
        data.Add(new DataModel()  {EmailId = "[email protected]", Name = "katrina", Gender = "Female", Salary = 10000 });
        return data.Where(x => x.Gender == Gender).ToList();
        //return data;
Don’t remember to add the line [System.Web.Script.Services.ScriptService] in your  service code behind. Otherwise, JavaScript would not have access to the above function (Getdata)
In the above code, I have created a list of type data model and have added various dummy data. Then based on the incoming paraamter ‘Gender’, I would return the filter data.

  3)    On the HTML side, I would add the following labels and a button to show the data
    <asp:Button ID="btnGetMsg" runat="server" Text="Click Me"   OnClientClick="DisplayMessageCall();return false;" />
  <asp:Label ID="txtName" runat="server" Text=""></asp:Label><br />
  <asp:Label ID="txtEmailId" runat="server" Text=""></asp:Label><br />
  <asp:Label ID="txtGender" runat="server" Text=""></asp:Label><br />
  <asp:Label ID="txtSalary" runat="server" Text=""></asp:Label><br />
  4)    On click of button, I would be calling javascript function DisplayMessageCall(). Code for this function is  
         var pageUrl = '<% =ResolveUrl("~/DBCall.asmx")%> '
            $.ajax( {
                type: "POST",
                url: pageUrl + "/GetData",
                data: "{'Gender':'Male'}",
                contentType: "application/json; charset=utf-8",
                dataType: "json",
                success: OnSuccessCall,
                error: OnErrorCall
As shown above, to make a json request
The request must be an HTTP POST request
The request’s content-type must be: “application/json; charset=utf-8″
Url will be your web service location followed by the method name
Data will consist of list of parameters to pas to web service call method. In this example, I am passing single parameter gender with value ‘male’. If there is no parameter then simply leave the data parameter as “\” which represents an empty JSON object
OnSuccessCall and OnErrorCall call is the name of the function which would be call on success and failure of web service data retrieval respectively.
  5)    Code for success and failure are  
        function OnSuccessCall(response)  {
            var Employees = response.d;
            $.each(Employees, function (index, employee)  {
                $('#<% = txtName.ClientID%> ').text($('#<% = txtName.ClientID%> ').text() + employee.Name + ',');
                $('#<% = txtEmailId.ClientID%> ').text($('#<% = txtEmailId.ClientID%> ').text() + employee.EmailId + ',');
                $('#<% = txtSalary.ClientID%> ').text($('#<% = txtSalary.ClientID%> ').text() + employee.Salary + ',');
                $('#<% = txtGender.ClientID%> ').text($('#<% = txtGender.ClientID%> ').text() + employee.Gender + ',');
        function OnErrorCall(response)  {
            alert(response.status + " " + response.statusText);
As you see above, in success method, I loaded the response from web service into a variable and then looped though the variable to displayed appended data in the four labels. On failure, I simply showed the alert message.
  6)    Now when I run the above example, then initially, my screen looks like
  7)    On click of the button, asynchronous web service call is made to display filtered data as
  8)    Now To check the failure scenario, I would not pass the gender parameters. In this case on click of the button, the screen will look like
Since jquery was not able to find the web method accepting zero parameter, it returned internal server error.

Thus, in this article, we saw how to show json data retrieved through web service using jquery ajax asynchronously.  

Note: Since JQuery is Javascript library <>, it is not recommended to retrieve large amount of data or do heavy database operations since it might hang your browser or make the browser unresponsive.  Example: If you want to retrive 7000 Records through web service then JQuery Ajax is not the recommended approach.  

Dowload Source Code
Note: Images used on this website are either a production of Bhaktivedanta Book Trust(, Iskcon Foundation or were found in google search under "Free to use and share". If any of the images presented here violates copyright issues or infringes anyone copyright or are not under "Fair use", then please bring it to our notice. Read Disclaimer for more.

Share this to your friends. One of your friend is waiting for your share.
Related Articles
Working with AJAX cascading dropdown
Database cannot be opened due to inaccessible files or insufficient memory or disk space
Trigger custom or manual postback in ASP.NET
Delete duplicate records from table in SQL
Call .net service from javascript
Get comma separated result of a database query
Ge the total number of HTML elements in a page
Manipulating Elements and Animations Using Jquery
Create property class of database table
Visitors-Hits counter for your website

Post Comment