Thursday, May 14, 2009

Accessing webservice from javascript using XML HTTp Activex

Define:

XML http is a active X object to enable the browser to sending the request and receiving the response asynchronously.

Example:

Aspx Section


<html>
<head>
<script type="text/javascript">
var xmlHttp=null;
function showHint(str)
{
if (str.length==0)
{
document.getElementById("txtHint").innerHTML="";
return;
}
try
{// Firefox, Opera 8.0+, Safari, IE7
xmlHttp=new XMLHttpRequest();
}
catch(e)
{// Old IE
try
{
xmlHttp=new ActiveXObject("Microsoft.XMLHTTP");
}
catch(e)
{
alert ("Your browser does not support XMLHTTP!");
return;
}
}
var url = "http://localhost:2735/call.asmx?op=HelloWorld";
//var getValue = document.getElementById("txt1");
//url = url + "&value='" + getValue.value + "'";

xmlHttp.onreadystatechange = output;
xmlHttp.open("GET",url,true);
xmlHttp.send();
function output() {
if (xmlHttp.readyState == 4)
{
xmlHttp.open("POST", "http://localhost:2735/call.asmx/HelloWorld", false);
xmlHttp.send();
document.getElementById("txtHint").innerHTML = xmlHttp.responseText;
}
}
}
</script>
</head>
<body>
<form>
First Name:
<input type="text" id="txt1"
onkeyup="showHint(this.value)">
</form><p>Suggestions: <span id="txtHint"></span></p> </body>
</html>

Webservice Section


namespace Xmlhttp
{
///
/// Summary description for call
///

[WebService(Namespace = "http://tempuri.org/")]
[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 call : System.Web.Services.WebService
{
[WebMethod]
public string HelloWorld()
{
string value = "1";// HttpContext.Current.Request.QueryString["value"];
Dictionary objDictionary = new Dictionary();
if (HttpRuntime.Cache["out"] != null)
{
objDictionary = (Dictionary)HttpRuntime.Cache["out"];
if (!objDictionary.ContainsKey(value))
{
objDictionary.Add(value, value + "out");
}
}
else
{
objDictionary.Add(value, value + "out");
}
HttpRuntime.Cache["out"] = objDictionary;
return objDictionary[value];
}
[WebMethod]
public string HelloWorld1(string value)
{
return value;
}
}
}