Wednesday, July 22, 2009

Ajax with webservice and javascript

[Write this in javascript]

function xmlhttpPost(strURL)
{
// alert(strURL)
var xmlHttpReq = false;
var self = this;
// Mozilla/Safari
if (window.XMLHttpRequest) {
self.xmlHttpReq = new XMLHttpRequest();
}
// IE
else if (window.ActiveXObject) {
self.xmlHttpReq = new ActiveXObject("Microsoft.XMLHTTP");
}
self.xmlHttpReq.open('POST', strURL, true);
self.xmlHttpReq.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
self.xmlHttpReq.onreadystatechange = function() {
if (self.xmlHttpReq.readyState == 4)
{
alert('hi');
updatepage(self.xmlHttpReq.responseText);
}
}
alert(getquerystring());
self.xmlHttpReq.send(getquerystring());
}

function getquerystring()
{
var form = document.forms['form1'];
var word = form.word.value;
qstr = 'w=' + escape(word); // NOTE: no '?' before querystring
return qstr;
}

function updatepage(str){
alert(str)
document.getElementById("result").innerHTML = str;
}

[Put some controls in HTML page under orm tag]

word:< name="word" type="text">
< value="Go" type="button" onclick="'JavaScript:xmlhttpPost(">
< id="result">< /div>


[ Create a webservice name it as WebService.asmx]

public class WebService : System.Web.Services.WebService {

public WebService () {

//Uncomment the following line if using designed components
//InitializeComponent();
}

[WebMethod]
public string HelloWorld(string w) {
return w;
}

}