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.
- using System;
- using System.Collections.Generic;
- using System.Linq;
- using System.Web;
- using System.Web.Script.Serialization;
- using System.Web.Script.Services;
- using System.Web.Services;
- using System.Xml.Linq;
- namespace DataReaderService
- {
- /// <summary>
- /// Summary description for EmpReader
- /// </summary>
- [WebService]
- //[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
- [System.ComponentModel.ToolboxItem(false)]
- // To allow this Web Service to be called from script, using ASP.NET AJAX, uncomment the following line.
- [System.Web.Script.Services.ScriptService]
- public class EmpReader : System.Web.Services.WebService
- {
- [WebMethod]
- [ScriptMethod(ResponseFormat = ResponseFormat.Json) ] //format the returned string value as JSON string
- public string getEmpData(string id)
- {
- //Create a list of 'employee' object
- List<employee> emps = new List<employee>();
- //Load the XML document
- var employee = XElement.Load( Server.MapPath("Employees.xml") );
- //Select the employee with given ID
- var emp = from q in employee.Elements("Employee")
- where q.Element("EmpId").Value == id
- select q;
- //Return a message to the client if no data returned
- if (emp.Count()==0) { return "no data"; }
- //Iterate through emp collection to populate a list of 'employee'
- foreach (var element in emp)
- {
- //Gets Phone elements
- var e = from j in element.Elements("Phone")
- select j;
- object[] phones = e.ToArray(); //Convert phone to array in order to be able to read their values only
- 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 });
- }
- //return emps;
- return new JavaScriptSerializer().Serialize(emps); //use this to return as JSON object
- }
- }
- public class employee
- {
- public string Name { get; set; }
- public string gender { get; set; }
- public string HomePhone { get; set; }
- public string WorkPhone { get; set; }
- public string Address { get; set; }
- }
- }
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
- var xhttp = new XMLHttpRequest();
- xhttp.onreadystatechange = function () {
- if (xhttp.readyState == 4 && xhttp.status == 200) {
- var server_data = xhttp.responseXML;
- //When using xhttp.responseXML, data can be returned in XML format , we get 'string' TAG contents
- var XMLData = server_data.getElementsByTagName("string")[0].childNodes[0].nodeValue;
- // //Check if data found
- if (XMLData != "no data") {
- $("#txtResult").val(XMLData);
- //parse JSON data
- var Result = JSON.parse(XMLData);
- //Draw Header
- $("#table_results").append("<tr><th>Name</th><th>Gender</th><th>Address</th><th>Home Phone</th><th>Work Phone</th></tr>");
- //Display data
- $("#txtResult").val(Result[0].Name);
- $("#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>");
- } else { $("#txtResult").val("No Data found"); }
- }
- };
- xhttp.open("POST", "http://localhost:56998/EmpReader.asmx/getEmpData", true);
- xhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
- xhttp.send("id=" + $("#txtEmpId").val() );
Using $.post method
- $.post("http://localhost:56998/EmpReader.asmx/getEmpData",
- { id: $("#txtEmpId").val() },
- function (data) {
- //Get data received from the server in XML format
- var data_packet = data.getElementsByTagName("string")[0].childNodes[0].nodeValue;
- //if invalid number sent, type an error message
- if (data_packet == "no data") $("#txtResult").val("No Data Found");
- else //if data found , draw the table
- {
- //parse JSON data
- var json_data = JSON.parse(data_packet);
- $("#txtResult").val(json_data[0].Name);
- //Draw the table
- //1. Draw the header
- $("#table_results").append("<tr><th>Name</th><th>Gender</th><th>Address</th><th>Home Phone</th><th>Work Phone</th></tr>");
- //Draw table body and write data
- $("#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>");
- }
- });
Using $.ajax method
- $.ajax({
- type: "POST",
- contentType: "application/json; charset=utf-8",
- url: "http://localhost:56998/EmpReader.asmx/getEmpData",
- data: '{id:"' + $("#txtEmpId").val() + '"}',
- dataType: "json",
- success: function (data) {
- //Check if there is data returned from the server
- if (data.d != "no data") {
- //return all data from the server
- var Result = JSON.parse(data.d);
- //Draw Header
- $("#table_results").append("<tr><th>Name</th><th>Gender</th><th>Address</th><th>Home Phone</th><th>Work Phone</th></tr>");
- $("#txtResult").val(Result[0].Name);
- $("#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>");
- } else { $("#txtResult").val("No data found"); } //return error message
- },
- error: function (result) {
- alert("Error reading data");
- }
- });
- var app = angular.module("NGMainApp", []);
- app.controller("MainController", function ($scope, $http) {
- $scope.LoadEmpData = function (variable) {
- document.getElementById("span1").innerText = variable;
- //*******
- var sentPacket = {
- method: 'POST',
- url: 'http://localhost:56998/EmpReader.asmx/getEmpData',
- headers: {
- 'Content-Type': 'application/json'
- },
- data: { "id": $scope.NGEmpID }
- }
- //*********
- $http(sentPacket).then(function (response) {
- //alert(response.data.d);
- if (response.data.d != "no data") {
- $scope.IsVisible = true;
- $scope.contents = JSON.parse(response.data.d);
- } else { $scope.IsVisible = false; }
- });
- }
- });
Notice: In methods 1 and 2, we get the response from the server as XML node and parse it as JSON data.

Hadshana KamalanathanPosted Jul 22, 2018, 1:19 AM
Good one...