Calling Web Services from HTML Pages using JavaScript in Visual Studio 2010

Steps

  • Go to New Project
  • Select Language Visual C#
  • Select Web
  • Select ASP .NET Empty Web Application
  • Give a proper Name to your Web App like WSFromHTMLusingJS

Now Add a HTML File to the Project.

For this, Right-click on the Project, choose Add a New Item, and choose the HTML template.

Name this like  AddNumbersForm.html

This is a simple HTML Form taking three Numbers as input parameters

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <title>Add Three Nos</title>

    <script type="text/javascript">

        function Init() {
            service.useService("WebService1.asmx?wsdl", "MyMath");      
        }

        var num1, num2, num3;

        function AddNos() {
            num1 = document.additionForm.num1.value;
            num2 = document.additionForm.num2.value;
            num3 = document.additionForm.num3.value;
            iCallID = service.MyMath.callService("AddThreeNos", num1, num2, num3);
        }

        function ShowResult() {
            alert(event.result.value);
        }
    </script>
</head>



 <body onload="Init()" id="service" style="behavior:url(webservice.htc)" onresult="ShowResult()">


<form name='additionForm'>

<table  cellpadding='10' align='center'>

<tr>
<td colspan="2" align="center">Add Three Numbers</td>
</tr>

<tr>
<td>Number 1: </td>

<td><input type="text" name ="num1" size="10" maxlength ="5" /> </td>

</tr>

<tr>
<td>Number 2: </td>

<td><input type="text" name ="num2" size="10" maxlength ="5" /></td>

</tr>

<tr>
<td>Number 3: </td>

<td><input type="text" name ="num3" size="10" maxlength ="5" /></td>

</tr>


<tr> <td colspan="2" align="center"><br/><br/>

<button onclick="AddNos()">Add</button>

<input type="reset" value ="Reset" />

</td></tr>

</table><br/><br/>


</form>

</body>
</html>

Now Add a Web Service to the Project

For this, Right-click on the Project, choose Add a New Item, and choose the Web Service template.

Name this WebServiceTest.asmx

When you create the web service by default you get a web method called Hello World.

Put this code below that and run your web service

[WebMethod]
        public int AddThreeNos(int num1, int num2, int num3)
        {
            return num1 + num2 + num3;
        }

Here to keep things simple we have created a very simple Web Service that returns the sum of three integer variables.

For calling webservices in HTML using JavaScript you need another file called webservice.htc
You can download this file from here.

webservice.htc

Web Service Behavior can be used to call remote methods from Web Services. The WebService behavior is implemented with an HTML Component (HTC) file as an attached behavior, so it can be used in Microsoft Internet Explorer 5 and later versions.

Download this file and put it in your Project Directory.

Run the project. You are done now. Congrats for Calling a WebService from an HTML Page using JavaScript.

Snapshot of the o/p

Addition No Form

Result from WebService

P.S-Try this only in Internet Explorer. You may not get the desired results in other browsers.

AJAX Example 4- Asynchronous Communication with XML using AJAX

//Program demonstrating asynchronous communication with an XML File using AJAX

Ajax4XML.html


<html>
<head>
<title>Ajax4 XML Example</title>
<script type="text/javascript">

var xmlhttp;

if (window.XMLHttpRequest)
  {
  xmlhttp=new XMLHttpRequest();
  }
else
  {
  xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
  }

function loadXMLDoc()
{
	var txt,first,i;

	if(xmlhttp){
	xmlhttp.open("GET","employee_data.xml",true);
	xmlhttp.onreadystatechange=function() {
	  if (xmlhttp.readyState==4 && xmlhttp.status==200) {
		var xmlDoc=xmlhttp.responseXML;
		txt="";
		first=xmlDoc.getElementsByTagName("first");
		for (i=0;i<first.length;i++) {
		  txt=txt + first[i].childNodes[0].nodeValue + "<br />";
		 }
		document.getElementById("myDiv").innerHTML=txt;
		}
	  }

	  xmlhttp.send(null);
	}
}//function end
</script>
</head>

<body>

<h2>Employee Data</h2>
<div id="myDiv"></div>
<br />
<button type="button" onclick="loadXMLDoc()">Get Employee Names</button>

</body>
</html>

employee_data.xml

<?xml version="1.0" encoding="UTF-8"?>

<employees>
	<employee position="manager">
		<name>
			<first>Meenakshi</first>
			<last>Das</last>
		</name>
		<age>31</age>
	</employee>
	<employee position="developer">
		<name>
			<first>Dia</first>
			<last>Agarwal</last>
		</name>
		<age>25</age>
	</employee>
	<employee position="developer">
		<name>
			<first>Natalie</first>
			<last>Abraham</last>
		</name>
		<age>23</age>
	</employee>
	<employee position="engineer">
		<name>
			<first>Kim</first>
			<last>Gentile</last>
		</name>
		<age>22</age>
	</employee>
	<employee position="accountant">
		<name>
			<first>Ankita</first>
			<last>Adhikary</last>
		</name>
		<age>25</age>
	</employee>
	<employee position="developer">
		<name>
			<first>Priya</first>
			<last>Kapoor</last>
		</name>
		<age>32</age>
	</employee>
</employees>

Snapshot of the o/p

AJAX Example 3- Asynchronous Communication using AJAX

//Program demonstrating Asynchronous Communication using AJAX

Ajax3.html


<html>
<head>
<title>Ajax 3</title>

<script type="text/javascript">

		var xmlhttp=false;

		if(window.XMLHttpRequest)
		{
			xmlhttp=new XMLHttpRequest();
		}
		else if(window.ActiveXObject)
		{
			xmlhttp=new ActiveXObject("Microsoft.XMLHttp");
		}

		function loadData(){

			 if(xmlhttp){
				xmlhttp.open("GET","ajax_info.txt",true);
				xmlhttp.onreadystatechange=function(){
				if (xmlhttp.readyState==4 && xmlhttp.status==200)
				{
					document.getElementById("Div1").innerHTML=xmlhttp.responseText;
				}
			  }
			xmlhttp.send();
		}//if

	  }//function end
</script>
</head>

<body>

<button type="button" onclick="loadData()">Change Content</button>

<div id="Div1">
<h2>Welcome to the world of AJAX</h2>
</div>

</body>

</html>

ajax_info.txt

AJAX= Asynchronous JavaScript and XML Allows for asynchronous communication between a browser (client) and server.
Does not mandate that the end user must wait for processing a request.
Can be used as an alternative to HTML forms in certain situations.

An asynchronous request is sent to the server and the contents of ajax_info.txt are sent to the client.

Screenshot of the o/p

This slideshow requires JavaScript.

AJAX Example 2- Synchronous Communication using AJAX

//Program demonstrating Synchronous Communication using AJAX

Ajax2.html


<html>
<head>
<title>Ajax2</title>

<script type="text/javascript">

		var xmlhttp=false;

		if(window.XMLHttpRequest)
		{
			xmlhttp=new XMLHttpRequest();
		}
		else if(window.ActiveXObject)
		{
			xmlhttp=new ActiveXObject("Microsoft.XMLHttp");
		}

		function loadData(){

		 if(xmlhttp)
		 {
			xmlhttp.open("GET","ajax_info.txt",false);
			xmlhttp.send();
			document.getElementById("Div1").innerHTML=xmlhttp.responseText;
		 }

		}
</script>
</head>

<body>

<div id="Div1">
<h2>Welcome to the world of AJAX</h2>

</div>

<button type="button" onclick="loadData()">Change Content</button>

</body>

</html>

ajax_info.txt

AJAX= Asynchronous JavaScript and XML Allows for asynchronous communication between a browser (client) and server.
Does not mandate that the end user must wait for processing a request.
Can be used as an alternative to HTML forms in certain situations.

When the button is clicked then the request is sent synchronously to the server and the contents of ajax_info.txt are sent to the client.

Screenshot of the o/p

AJAX Example 1- Creating XMLHttp Request Object

//AJAX Program demonstrating how to create an XMLHttpRequest object

Ajax1.html


<html>
<head>
<title>Ajax Example 1</title>

<script type="text/javascript">

		var xmlhttp=false;

		if(window.XMLHttpRequest)
		{// code for IE7+, Firefox, Chrome, Opera, Safari
			xmlhttp=new XMLHttpRequest();
		}
		else if(window.ActiveXObject)
		{// code for IE6, IE5
			xmlhttp=new ActiveXObject("Microsoft.XMLHttp");
		}
		//Now you can start writing HTML as usual, after checking for the presence of the XMLHttpRequest object

		if(xmlhttp)
		{
			document.write("<h1>Hello World from AJAX</h1>");
		}

</script>

</head>

<body>

</body>

</html>

You can double click the the above program to run it just like any other HTML file.

Snapshot of the o/p

Ajax1