Practical Approach To ASP.NET Web Services - Part Six - Calling ASP.NET Web Service From Java Script Using AJAX

Introduction

 
This article is in continuation of my previous articles of the "Practical Approach To ASP.NET Web Services" series. So, we will be using the same examples again.
  1. Practical Approach To ASP.NET Web Services - Part One - Overview
  2. Practical Approach To ASP.NET Web Services - Part Two - Consuming A Web Service
  3. Practical Approach To ASP.NET Web Services - Part Three - Session State In A Web Service
  4. Practical Approach To ASP.NET Web Services - Part Four - Web Method Attribute Properties
  5. Practical Approach To ASP.NET Web Services - Part Five - Web Method Overloading
First, we will create a table called Students.
  1. CreateTable tblStudents(ID intidentityprimarykey, Namenvarchar(50), Gender nvarchar(20), TotalMarks int)   
Now, we will insert some values in it.
  1. Insertinto tblStudents values('Akshay''Male', 900)    
  2. Insertinto tblStudents values('Milind''Female', 760)    
  3. Insertinto tblStudents values('Raghvan''Male', 980)    
  4. Insertinto tblStudents values('Umesh''Male', 990)    
  5. Insertinto tblStudents values('Gopal''Male', 440)   
So, we have the following output.
 
output
 
The next step is to create a procedure.
  1. CreateProc spGetStudentByID    
  2. @ID int    
  3. as    
  4. Begin    
  5. Select ID, Name, Gender, TotalMarks    
  6. from tblStudents where ID = @ID    
  7. End   
Now, we have a stored procedure that will retrieve information by its ID.The name of the stored procedure is spGetStudentByID and it’s a simple straight forward Stored Procedure.
 
Next, let's create an empty application and add a class file (Student.cs) and a container class having get and set properties.
 
output
 
The next step is to add a Web Service.
 
Right-click on project in the Solution Explorer and add a Web Service. Name it as StudentService.asmx.
 
Copy and paste the following code in StudentService.asmx.cs file. Make sure [System.Web.Script.Services.ScriptService] attribute is included. This attribute allows a web service to be called from JavaScript using ASP.NET AJAX.
 
JavaScript
 
It’s a simple straight forward ADO.NET code where we had included Student object and initiated that we had passed the connection string which we had passed in our Web.config file.
 
Then, we used the SqlConnection object to initialize the connection and passed the SQL command to pass our stored procedure. It's expecting a parameter, so we passed a parameter as ID, and then we are opening our connection. Next, we are looping through each record.
 
Now, let's quickly check our Web Service and try to invoke it by ID.
 
JavaScript
 
So from the above output, our Web Service is working properly.
 
The next step is to add a web form. Right-click the project in the Solution Explorer and add a web form. This should add WebForm1.aspx.
 
Copy and paste the following HTML between the opening and closing <html></html> tags in WebForm1.aspx.
  1. <htmlxmlns="http://www.w3.org/1999/xhtml">    
  2.     <headrunat="server">    
  3.         <title></title>    
  4.         <scripttype="text/javascript" language="javascript"function GetStudentById() { var id = document.getElementById("txtStudentId").value; Webservice.StudentService.GetStudentByID(id, GetStudentByIdSuccessCallback, GetStudentByIdFailedCallback); } function GetStudentByIdSuccessCallback(result) { document.getElementById("txtName").value = result["Name"]; document.getElementById("txtGender").value = result["Gender"]; document.getElementById("txtTotalMarks").value = result["TotalMarks"]; } function GetStudentByIdFailedCallback(errors) { alert(errors.get_message()); } </script>    
  5.             </head>    
  6.     
  7.             <body>    
  8.                 <formid="form1" runat="server">    
  9.                     <asp:ScriptManagerID="ScriptManager1" runat="server">    
  10.                         <Services>    
  11.                             <asp:ServiceReferencePath="~/StudentService.asmx" /> </Services>    
  12.                         </asp:ScriptManager>    
  13.                         <tablestyle="font-family:Arial; border:1px solid black">    
  14.                             <tr>    
  15.                                 <td><b>ID</b></td>    
  16.                                 <td>    
  17.                                     <asp:TextBoxID="txtStudentId" runat="server"></asp:TextBox>    
  18.                                         <inputid="Button1" type="button" value="Get Student" onclick="GetStudentById()" /> </td>    
  19.                             </tr>    
  20.                             <tr>    
  21.                                 <td><b>Name</b></td>    
  22.                                 <td>    
  23.                                     <asp:TextBoxID="txtName" runat="server"></asp:TextBox>    
  24.                                 </td>    
  25.                             </tr>    
  26.                             <tr>    
  27.                                 <td><b>Gender</b></td>    
  28.                                 <td>    
  29.                                     <asp:TextBoxID="txtGender" runat="server"></asp:TextBox>    
  30.                                 </td>    
  31.                             </tr>    
  32.                             <tr>    
  33.                                 <td><b>Total Marks</b></td>    
  34.                                 <td>    
  35.                                     <asp:TextBoxID="txtTotalMarks" runat="server"></asp:TextBox>    
  36.                                 </td>    
  37.                             </tr>    
  38.                             </table>    
  39.                             <asp:LabelID="lblPageTime" runat="server"></asp:Label>    
  40.                                 </form>    
  41.             </body>    
  42.     
  43.             </html>   
Now, let's try to understand the code. We have added script manager control. In that, we have given the respective path of our web service. Now, in our table tag, we have to specify the id and click on Get details buttons. Our webservice will fetch the data with the help of AJAX.
 
Now, in a script tag, we will create a function as GetstudentByid and we will be passing id. If it exists in the database, then it will call another function GetStudentByIdSuccessCallback and will return the details from the database, otherwise, it will raise an error.
 
Now, let's run our app and see the output.
 
JavaScript

Summary

 
As you can see from the above output, we have entered ID as 1 and clicked on GetStudent. The other details like Name, Gender, and Total marks are fetched from the database and are displayed in the respective textbox.