Save Records Using jQuery, Web Services, and JSON Objects

Introduction

Before going in detail of this article I would like to introduce you the technologies used in the example.

Jquery: JQuery is a JavaScript Library, it greatly simplifies JavaScript programming.

Web Services:
A web service is the communication platform between two different platform applications that allows using their web method.

JSON:

  • JSON stands for JavaScript Object Notation
  • JSON is a lightweight data-interchange format
  • JSON is language independent *
  • JSON is "self-describing" and easy to understand

Note: For better understanding of jQuery you must have the knowledge of CSS and JavaScripts.

Descriptions

Here are the files we have to create:

Files

Step 1: Create an HTML Page Design Page:

  1. <!DOCTYPE html>  
  2. <html xmlns="http://www.w3.org/1999/xhtml">  
  3. <head>  
  4.     <title></title>  
  5.     <script src="jquery-1.11.3.js"></script>  
  6.     <script src="MyJsCode.js"></script>  
  7.     <style type="text/css">  
  8.         .auto-style1 {  
  9.             width: 72px;  
  10.         }  
  11.         .auto-style2 {  
  12.             width: 53px;  
  13.         }  
  14.     </style>  
  15. </head>  
  16. <body style="background-color:ActiveBorder">  
  17.     <form id="form1" style="height: 500px; width: 500px;background-image:url('img/p2.jpg'); border:solid;  
  18.  border-collapse:collapse;margin-top:120px; margin-left:400px;">  
  19.         <div id="div1" style="height: 170px; width: 500px;">  
  20.             <p style="margin-left:100px; font-family:Algerian;">Enter Name and Salary Below !</p>  
  21.             <table id="tbl1" border="1" style="margin-left: 130px; margin-top: 30px">  
  22.                 <tr>  
  23.                     <td>Name</td>  
  24.                     <td>  
  25.                         <input id="txtname" type="text" /></td>  
  26.                 </tr>  
  27.                 <tr>  
  28.                     <td>Salary</td>  
  29.                     <td>  
  30.                         <input id="txtsalary" type="text" /></td>  
  31.                 </tr>  
  32.                 <tr>  
  33.                     <td colspan="2">  
  34.                         <input id="btnSave" type="button" value="Save" style="margin-left: 10px; width: 150px" />  
  35.                     </td>  
  36.                 </tr>  
  37.             </table>  
  38.             <br />  
  39.         </div>  
  40.         <div id="div2" style="height: 250px; width: 500px">  
  41.             <p style="margin-left:150px; font-family:Algerian;">Employee Records</p>  
  42.             <table id="tbl2" border="1" style="border-collapse: collapse; margin-left: 135px; width: 200px;">  
  43.                 <thead>  
  44.                     <tr>  
  45.                         <th class="auto-style2">ID</th>  
  46.                         <th>Name</th>  
  47.                         <th class="auto-style1">Salary</th>  
  48.                     </tr>  
  49.                 </thead>  
  50.                 <tbody>  
  51.                 </tbody>  
  52.             </table>  
  53.         </div>  
  54.     </form>  
  55. </body>  
  56. </html>

Step 2: After designing the Web Page, let's create a table in SQL Server to save data.

result

Step 3: Create a user defined type (or class) to accept the user value:

  1. public class Employee  
  2. {  
  3.    public int ID { getset; }  
  4.    public string Name { getset; }  
  5.   
  6.    public int Salary { getset; }  
  7.   

Step 4: We have created a web service having two Web Methods with ADO.NET class to communicate with SQL Server from HTML Page.

  1. public class My : System.Web.Services.WebService  
  2. {  
  3.     string CS = ConfigurationManager.ConnectionStrings["MyCon"].ConnectionString;  
  4.     //Below method will accept employee type object and save it DB.  
  5.     [WebMethod]  
  6.     public void saveData(Employee emp1)  
  7.     {  
  8.         SqlConnection _con = new SqlConnection(CS);  
  9.         SqlCommand _cmd = new SqlCommand("insert into Employees values(@name,@salary)", _con);  
  10.         _cmd.Parameters.AddWithValue("@name", emp1.Name);  
  11.         _cmd.Parameters.AddWithValue("@salary", emp1.Salary);  
  12.         _con.Open();  
  13.         int i = _cmd.ExecuteNonQuery();  
  14.         _con.Close();  
  15.     }  
  16.     //This method has used to select the employee record and store in collection.  
  17.     [WebMethod]  
  18.     public void GetEmployeeRecord()  
  19.     {  
  20.         List<Employee> _li = new List<Employee>();  
  21.         SqlConnection _con = new SqlConnection(CS);  
  22.         SqlCommand _cmd = new SqlCommand("select * from Employees", _con);  
  23.         _con.Open();  
  24.         SqlDataReader dr = _cmd.ExecuteReader();  
  25.         while (dr.Read())  
  26.         {  
  27.             Employee emp = new Employee();  
  28.             emp.ID = Convert.ToInt32(dr[0]);  
  29.             emp.Name = dr[1].ToString();  
  30.             emp.Salary = Convert.ToInt32(dr[2]);  
  31.   
  32.             _li.Add(emp);     
  33.         }  
  34.         _con.Close();  
  35. //JavaScriptSerializer class has used to convert list collection to JSON array.  
  36.         JavaScriptSerializer js = new JavaScriptSerializer();  
  37.         Context.Response.Write(js.Serialize(_li));  
  38.     }  
  39.   
  40. }

Web Services will look like.

Step 5: Finally, create a javascript file for jQuery functions.

Here we have created two functions like webservices:

  1. //TO Save the User Data  
  2. $(document).ready(function () {  
  3.     $("#btnSave").click(function () {  
  4.         var employee = {};  
  5.         employee.Name = $("#txtname").val();  
  6.         employee.Salary = $("#txtsalary").val();  
  7.   
  8.         $.ajax({  
  9.             url: 'My.asmx/saveData',  
  10.             method: 'post',  
  11.             contentType: 'application/json;Charset=utf-8',  
  12.             data: '{emp1:' + JSON.stringify(employee) + '}',  
  13.             success: function () {  
  14.                 show();  
  15.                 $("#txtname").val("");  
  16.                 $("#txtsalary").val("");  
  17.             },  
  18.             error: function (err) {  
  19.                 alert("Please Enter Name and Salary");  
  20.                   
  21.             }  
  22.         });  
  23.     });  
  24. });  
  25. //TO Display the Records  
  26. function show() {  
  27.     $.ajax({  
  28.         url: 'My.asmx/GetEmployeeRecord',  
  29.         dataType: "json",  
  30.         method: 'post',  
  31.         success: function (data) {  
  32.             var employee = $("#tbl2 tbody");  
  33.             employee.empty();  
  34.             $(data).each(function (index, emp) {  
  35.                 employee.append('<tr><td>' + emp.ID + '</td><td>' + emp.Name + '</td><td>' + emp.Salary + '</td></tr>');  
  36.             });  
  37.         },  
  38.         error: function (err) {  
  39.             alert(err);  
  40.         }  
  41.     });  
  42. }

To successfully execution of jQuery codes, please download the latest jQuery script file form jquery.com.

Output:

Output

Hope you liked this article.

Up Next
    Ebook Download
    View all
    Learn
    View all