Using Web Service From Client- Side Code

Before you begin with the client-side code, you should have a server code that will respond to all the requests coming from your client-server code. In this case, I've created a web service to handle the requests. Notice the green comments.

  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.Linq;  
  4. using System.Web;  
  5. using System.Web.Script.Serialization;  
  6. using System.Web.Script.Services;  
  7. using System.Web.Services;  
  8. using System.Xml.Linq;  
  9.   
  10. namespace DataReaderService  
  11. {  
  12.     /// <summary>  
  13.     /// Summary description for EmpReader  
  14.     /// </summary>  
  15.     [WebService]  
  16.     //[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]  
  17.     [System.ComponentModel.ToolboxItem(false)]  
  18.     // To allow this Web Service to be called from script, using ASP.NET AJAX, uncomment the following line.   
  19.     [System.Web.Script.Services.ScriptService]  
  20.     public class EmpReader : System.Web.Services.WebService  
  21.     {  
  22.         [WebMethod]  
  23.         [ScriptMethod(ResponseFormat = ResponseFormat.Json) ] //format the returned string value as JSON string  
  24.         public string getEmpData(string id)  
  25.         {  
  26.             //Create a list of 'employee' object  
  27.             List<employee> emps = new List<employee>();  
  28.   
  29.             //Load the XML document  
  30.             var employee = XElement.Load( Server.MapPath("Employees.xml") );  
  31.   
  32.             //Select the employee with given ID  
  33.             var emp = from q in employee.Elements("Employee")  
  34.                       where q.Element("EmpId").Value == id  
  35.                       select q;  
  36.   
  37.             //Return a message to the client if no data returned  
  38.             if (emp.Count()==0) { return "no data";  }  
  39.   
  40.             //Iterate through emp collection to populate a list of 'employee'  
  41.             foreach (var element in emp)  
  42.             {  
  43.                 //Gets Phone elements  
  44.                 var e = from j in element.Elements("Phone")                          
  45.                         select j;  
  46.   
  47.                 object[] phones = e.ToArray(); //Convert phone to array in order to be able to read their values only  
  48.   
  49.                 emps.Add(new employee { Name = element.Element("Name").Value, gender = element.Element("Sex").Value, Address = element.Element("Address").Value, HomePhone = ((XElement)phones[0]).Value , WorkPhone=((XElement)phones[1]).Value });  
  50.             }  
  51.   
  52.             //return emps;  
  53.             return new JavaScriptSerializer().Serialize(emps); //use this to return as JSON object  
  54.         }  
  55.     }  
  56.   
  57.     public class employee  
  58.     {  
  59.         public string Name { getset; }  
  60.         public string gender { getset; }  
  61.         public string HomePhone { getset; }  
  62.         public string WorkPhone { getset; }  
  63.         public string Address { getset; }  
  64.     }  
  65. }  

You may change how the server handles the requests to add more functionality. Now it's time to write our client-side code, and here are some different ways:

Classic JavaScript

  1. var xhttp = new XMLHttpRequest();  
  2.         xhttp.onreadystatechange = function () {  
  3.             if (xhttp.readyState == 4 && xhttp.status == 200) {                  
  4.                 var server_data = xhttp.responseXML;  
  5.   
  6.                 //When using xhttp.responseXML, data can be returned in XML format , we get 'string' TAG contents  
  7.                 var XMLData = server_data.getElementsByTagName("string")[0].childNodes[0].nodeValue;  
  8.   
  9.         //        //Check if data found  
  10.                 if (XMLData != "no data") {  
  11.                     $("#txtResult").val(XMLData);  
  12.   
  13.                    //parse JSON data  
  14.                     var Result = JSON.parse(XMLData);  
  15.   
  16.                     //Draw Header  
  17.                    $("#table_results").append("<tr><th>Name</th><th>Gender</th><th>Address</th><th>Home Phone</th><th>Work Phone</th></tr>");  
  18.   
  19.                     //Display data  
  20.                    $("#txtResult").val(Result[0].Name);  
  21.                    $("#table_results").append("<tr><td>" + Result[0].Name + "</td><td>" + Result[0].gender + "</td><td>" + Result[0].Address + "</td><td>" + Result[0].HomePhone + "</td><td>" + Result[0].WorkPhone + "</td></tr>");  
  22.   
  23.   
  24.                 } else { $("#txtResult").val("No Data found"); }  
  25.             }  
  26.         };  
  27.         xhttp.open("POST""http://localhost:56998/EmpReader.asmx/getEmpData"true);  
  28.         xhttp.setRequestHeader("Content-type""application/x-www-form-urlencoded");  
  29.         xhttp.send("id=" + $("#txtEmpId").val() );  

Using $.post method

  1. $.post("http://localhost:56998/EmpReader.asmx/getEmpData",  
  2.             { id: $("#txtEmpId").val() },  
  3.             function (data) {  
  4.                 //Get data received from the server in XML format  
  5.                 var data_packet = data.getElementsByTagName("string")[0].childNodes[0].nodeValue;  
  6.   
  7.                 //if invalid number sent, type an error message  
  8.                 if (data_packet == "no data") $("#txtResult").val("No Data Found");  
  9.                 else //if data found , draw the table  
  10.                 {  
  11.                     //parse JSON data  
  12.                     var json_data = JSON.parse(data_packet);  
  13.   
  14.                     $("#txtResult").val(json_data[0].Name);  
  15.   
  16.                     //Draw the table  
  17.                     //1. Draw the header  
  18.                     $("#table_results").append("<tr><th>Name</th><th>Gender</th><th>Address</th><th>Home Phone</th><th>Work Phone</th></tr>");  
  19.   
  20.                     //Draw table body and write data  
  21.                     $("#table_results").append("<tr><td>" + json_data[0].Name + "</td><td>" + json_data[0].gender + "</td><td>" + json_data[0].Address + "</td><td>" + json_data[0].HomePhone + "</td><td>" + json_data[0].WorkPhone + "</td></tr>");  
  22.                 }  
  23.                   
  24.             });  

Using $.ajax method 

  1. $.ajax({  
  2.             type: "POST",  
  3.             contentType: "application/json; charset=utf-8",  
  4.             url: "http://localhost:56998/EmpReader.asmx/getEmpData",  
  5.             data: '{id:"' + $("#txtEmpId").val() + '"}',  
  6.             dataType: "json",  
  7.             success: function (data) {  
  8.   
  9.                 //Check if there is data returned from the server  
  10.                 if (data.d != "no data") {  
  11.   
  12.                     //return all data from the server  
  13.                     var Result = JSON.parse(data.d);  
  14.   
  15.                     //Draw Header  
  16.                     $("#table_results").append("<tr><th>Name</th><th>Gender</th><th>Address</th><th>Home Phone</th><th>Work Phone</th></tr>");  
  17.   
  18.                     $("#txtResult").val(Result[0].Name);  
  19.                     $("#table_results").append("<tr><td>" + Result[0].Name + "</td><td>" + Result[0].gender + "</td><td>" + Result[0].Address + "</td><td>" + Result[0].HomePhone + "</td><td>" + Result[0].WorkPhone + "</td></tr>");  
  20.                 } else { $("#txtResult").val("No data found"); } //return error message  
  21.             },  
  22.             error: function (result) {  
  23.                 alert("Error reading data");  
  24.             }  
  25.         });  
Using AngularJS 
  1. var app = angular.module("NGMainApp", []);  
  2.   
  3.   
  4. app.controller("MainController"function ($scope, $http) {  
  5.   
  6.       
  7.   
  8.     $scope.LoadEmpData = function (variable) {  
  9.         document.getElementById("span1").innerText = variable;  
  10.   
  11.         //*******  
  12.         var sentPacket = {  
  13.             method: 'POST',  
  14.             url: 'http://localhost:56998/EmpReader.asmx/getEmpData',  
  15.             headers: {  
  16.                 'Content-Type''application/json'  
  17.             },  
  18.             data: { "id": $scope.NGEmpID }  
  19.         }  
  20.         //*********  
  21.         $http(sentPacket).then(function (response) {  
  22.               
  23.             //alert(response.data.d);  
  24.             if (response.data.d != "no data") {  
  25.                 $scope.IsVisible = true;  
  26.                 $scope.contents = JSON.parse(response.data.d);  
  27.             } else { $scope.IsVisible = false; }  
  28.   
  29.         });  
  30.     }  
  31.   
  32. });  

Notice: In methods 1 and 2, we get the response from the server as XML node and parse it as JSON data.

Due to the size limit, I uploaded the project here
 
Decryption code: !1GKQNhG3V4OT3EstM14ayPYd6-j4VOz7ry_c_UKUpIw
Ebook Download
View all
Learn
View all