Perform JSON based CRUD operations using WCF REST Services - using JQuery

by Jagadish Pulakhandam on 2/6/2012 7:35:03 AM
Rated 0 from 0 votes
Brief: Demonstrates consuming a WCF REST service (with JSON based communication) using a simple HTML file with plain JQuery script
Posted to: Consuming WCF REST Services
Add to DiggAdd to del.icio.usAdd to FURLAdd to RedditAdd to YahooAdd to BlinklistAdd to GoogleAdd to ma.gnoliaAdd to ShadowsAdd to Technorati

The script demonstrates the following:
  • How to fetch data from WCF REST service using JQuery (using HTTP GET operations)
  • How to add (or insert) data using WCF REST Service with JQuery (using HTTP POST operation)
  • How to update data using WCF REST Service with JQuery (using HTTP PUT operation)
  • How to delete data using WCF REST Service with JQuery (using HTTP DELETE operation)
  • All scripts using plain HTML 
NOTE: The samples use JSON to communicate to WCF REST service.  Check "Related Posts" section for XML based communications. The source code of WCF REST Service is already provided in previous articles (check "Related Posts" section).

Source code to fetch all employees:

01.<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
03.<head>
04.    <title></title>
05.        <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js" type="text/javascript"></script>
06.        <script type="text/javascript">
07. 
08.          function GetEmployeeInformation() {
09.              $.ajax({
10.                  type: "GET",
11.                  url: "http://localhost:8080/SampleEmpService/Employees",
12.                  contentType: "application/json; charset=utf-8",
13.                  cache:false,
14.                  dataType:"json",
15.                  error: function (xhr, ajaxOptions, thrownError) {
16.                      alert(xhr.status);
17.                      alert(xhr.statusText);
18.                      alert(thrownError)
19.                  },
20.                  success: function (response) {
21.                       
22.                      $("#divEmployeeInfo").html("");
23.                      for(emp in response)
24.                      {
25.                        $("#divEmployeeInfo").append("Id: ").append(response[emp].Empno + "<br />");
26.                        $("#divEmployeeInfo").append("Name: ").append(response[emp].Ename + "<br />");
27.                        $("#divEmployeeInfo").append("Sal: ").append(response[emp].Sal + "<br />");
28.                        $("#divEmployeeInfo").append("Deptno: ").append(response[emp].Deptno + "<br />");
29.                        $("#divEmployeeInfo").append("<hr />");
30.                      }
31.                       
32.                      //another way
33.                      $.each(response, function (i, v) {
34.                          for (var key in v) {
35.                              $("#divEmployeeInfo").append(key + ": " + v[key] + "<br />" );
36.                          }
37.                          $("#divEmployeeInfo").append("<hr />");
38.                      });
39.                  }
40.              });
41.          }
42. 
43.</script>
44. 
45.</head>
46.<body>
47.    <input id="btnGetEmpList" value="Get Employee List" type="button" onClick="GetEmployeeInformation();" />
48.    <br /><br />
49.    <div id="divEmployeeInfo"></div>
50. 
51.</body>
52.</html>

Source code to fetch/display a single row (based on a condition):

01.<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
03.<head>
04.    <title></title>
05.        <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js" type="text/javascript"></script>
06.        <script type="text/javascript">
07. 
08.          function GetEmployeeInformation() {
09.              $.ajax({
10.                  type: "GET",
11.                  url: "http://localhost:8080/SampleEmpService/Employees/" + $("#txtEmpno").val(),
12.                  contentType: "application/json; charset=utf-8",
13.                  cache:false,
14.                  dataType:"json",
15.                  error: function (xhr, ajaxOptions, thrownError) {
16.                      alert(xhr.status);
17.                      alert(xhr.statusText);
18.                      alert(thrownError)
19.                  },
20.                  success: function (response) {
21.                      $("#divEmployeeInfo").html("");
22.                      $("#divEmployeeInfo").append("Id: ").append(response.Empno + "<br />");
23.                      $("#divEmployeeInfo").append("Name: ").append(response.Ename + "<br />");
24.                      $("#divEmployeeInfo").append("Salary: ").append(response.Sal + "<br />");
25.                      $("#divEmployeeInfo").append("Deptno: ").append(response.Deptno + "<br />");
26.                  }
27.              });
28.          }
29. 
30.</script>
31. 
32.</head>
33.<body>
34.    Enter Employee Id:
35.    <input id="txtEmpno"/>
36.    <input id="btnGetEmployee" value="Get Employee Details" type="button" onClick="GetEmployeeInformation();" />
37.    <br /><br />
38.    <div id="divEmployeeInfo"></div>
39. 
40.</body>
41.</html>

Source code to add/insert a new row:

01.<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
03.<head>
04.    <title></title>
05.        <script src="http://ajax.cdnjs.com/ajax/libs/json2/20110223/json2.js" type="text/javascript"></script>
06.        <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js" type="text/javascript"></script>
07.        <script type="text/javascript">
08. 
09.          function AddEmployeeInfo() {
10.              var postParams = {};
11.              postParams["Empno"] = $('#txtEmpno').val();
12.              postParams["Ename"] = $('#txtEname').val();
13.              postParams["Sal"] = $('#txtSal').val();
14.              postParams["Deptno"] = $('#txtDeptno').val();
15.               
16.              $.ajax({
17.                  type: "POST",
18.                  url: "http://localhost:8080/SampleEmpService/Employees",
19.                  contentType: "application/json; charset=utf-8",
20.                  data: JSON.stringify(postParams),
21.                  error: function (xhr, ajaxOptions, thrownError) {
22.                      alert(xhr.status);
23.                      alert(xhr.statusText);
24.                      alert(thrownError)
25.                  },
26.                  success: function (response) {
27.                    alert("Successfully Added");
28.                  }
29.              });
30.          }
31. 
32.</script>
33. 
34.</head>
35.<body>
36.    Id:     <input id="txtEmpno"> <br />
37.    Name:   <input id="txtEname"> <br />
38.    Salary: <input id="txtSal"> <br />
39.    Deptno: <input id="txtDeptno"> <br /><br />
40.    <input id="btnAdd" value="Add Employee" type="button" onClick="AddEmployeeInfo();" />
41.    <br /><br />
42.    <div id="divEmployeeInfo"></div>
43. 
44.</body>
45.</html>

01.<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
03.<head>
04.    <title></title>
05.        <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js" type="text/javascript"></script>
06.        <script type="text/javascript">
07.           
08.          function GetEmployeeInformation() {
09.              $("#txtEname").val("");
10.              $("#txtSal").val("");
11.              $("#txtDeptno").val("");
12.              $.ajax({
13.                  type: "GET",
14.                  url: "http://localhost:8080/SampleEmpService/Employees/" + $("#txtEmpno").val(),
15.                  contentType: "application/json; charset=utf-8",
16.                  cache:false,
17.                  dataType:"json",
18.                  error: function (xhr, ajaxOptions, thrownError) {
19.                      alert(xhr.status);
20.                      alert(xhr.statusText);
21.                      alert(thrownError)
22.                  },
23.                  success: function (response) {
24.                    $("#txtEname").val(response.Ename);
25.                    $("#txtSal").val(response.Sal);
26.                    $("#txtDeptno").val(response.Deptno);
27.                  }
28.              });
29.          }
30.           
31.          function UpdateEmployeeInfo() {
32.              var postParams = {};
33.              postParams["Empno"] = $('#txtEmpno').val();
34.              postParams["Ename"] = $('#txtEname').val();
35.              postParams["Sal"] = $('#txtSal').val();
36.              postParams["Deptno"] = $('#txtDeptno').val();
37.               
38.              $.ajax({
39.                  type: "PUT",
40.                  url: "http://localhost:8080/SampleEmpService/Employees",
41.                  contentType: "application/json; charset=utf-8",
42.                  data: JSON.stringify(postParams),
43.                  error: function (xhr, ajaxOptions, thrownError) {
44.                      alert(xhr.status);
45.                      alert(xhr.statusText);
46.                      alert(thrownError)
47.                  },
48.                  success: function (response) {
49.                    alert("Successfully Updated");
50.                  }
51.              });
52.          }
53. 
54.          function DeleteEmployeeInfo() {
55.              $("#txtEname").val("");
56.              $("#txtSal").val("");
57.              $("#txtDeptno").val("");
58.              $.ajax({
59.                  type: "DELETE",
60.                  url: "http://localhost:8080/SampleEmpService/Employees/" + $("#txtEmpno").val(),
61.                  contentType: "application/json; charset=utf-8",
62.                  error: function (xhr, ajaxOptions, thrownError) {
63.                      alert(xhr.status);
64.                      alert(xhr.statusText);
65.                      alert(thrownError)
66.                  },
67.                  success: function (response) {
68.                    alert("Successfully Deleted");
69.                  }
70.              });
71.          }
72. 
73.</script>
74. 
75.</head>
76.<body>
77.    Id:     <input id="txtEmpno">
78.    <input id="btnGetEmployee" value="Get Employee Details" type="button" onClick="GetEmployeeInformation();" /> <br />
79.    Name:   <input id="txtEname"> <br />
80.    Salary: <input id="txtSal"> <br />
81.    Deptno: <input id="txtDeptno"> <br /><br />
82.    <input id="btnUpdate" value="Save Employee" type="button" onClick="UpdateEmployeeInfo();" />
83.    <input id="btnDelete" value="Delete Employee" type="button" onClick="DeleteEmployeeInfo();" />
84.    <br /><br />
85.    <div id="divEmployeeInfo"></div>
86. 
87.</body>
88.</html>

Join the .NET Code Central Community and join the discussion!
Signing-up is FREE and quick. Do it now, we want to hear your opinion
4

Rated 0 from 0 votes ( login  to rate)
DotnetKicks DotnetKicksDe DotNetShoutout

Attachments / Source Code
You need to Login or Join for FREE to download the following