Call Asp.net Page Method Without Microsoft Ajax, without j query
Have you ever thought that we can call the web method without using j query, or Microsoft Ajax, This tutorial will help you lot to understand the Ajax in asp.netDefault.aspx
<button onclick="javascript:callWebMethod();">
GetName</button>
This button will call the callWebMethod() javascript method
Default.aspx.cs
Lets call GetName method using javascript
//I will call this method from client code using java script
[WebMethod]
public static string GetName(string name)
{
return "Hello " + name;
}
Javascript Code
//name is the parameter in GetName Web method
//vijay is the parameter value
var data = '{"name":"vijay"}';
//I will call this method on above button click event
function callWebMethod() {
var xmlhttp = createXMLHTTPObject();
xmlhttp.onreadystatechange = function () {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
alert(xmlhttp.responseText);
}
}
xmlhttp.send(data);
}
//this function will create xmlhttpobject
function createXMLHTTPObject() {
var xmlhttp;
if (window.XMLHttpRequest) {// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp = new XMLHttpRequest();
}
else {
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
//I will make the post request to the page to send json formatted data
xmlhttp.open("POST", "Default.aspx/GetName", true);
xmlhttp.setRequestHeader("Host", window.location.host);
xmlhttp.setRequestHeader("Content-Type", "application/json; charset=utf-8");
xmlhttp.setRequestHeader("Content-Length", data.length);
xmlhttp.setRequestHeader("dataType", "Json");
return xmlhttp;
}
Comments
Post a Comment