In the example we are going to write a method to get the current time as a server side method, make an AJAX call to the server and executes the GetCurrentTime method.
Below is our HTML markup. TextBox to enter name and a button to execute the call
<div>
Your Name :
<asp:TextBox ID="txtUserName" runat="server"></asp:TextBox>
<input id="btnGetTime" type="button" value="Show Current Time"
onclick = "ShowCurrentTime()" />
</div>
Below is our client side code.
<script type="text/javascript">
function ShowCurrentTime() {
$.ajax({
type: "POST", // Request type
url: "Jquery.aspx/GetCurrentTime", //Page URL/Method name
data: '{name: "' + $("#<%=txtUserName.ClientID%>")[0].value + '" }', // parameter
contentType: "application/json; charset=utf-8",
dataType: "json",
success: OnSuccess,//success method
failure: function (response) {
alert(response.d);
}
});
}
function OnSuccess(response) {
alert(response.d);
}
</script>
Below is our server side code. Note that this method is declared as static and a WebMethod
Your Name :
<asp:TextBox ID="txtUserName" runat="server"></asp:TextBox>
<input id="btnGetTime" type="button" value="Show Current Time"
onclick = "ShowCurrentTime()" />
</div>
Below is our client side code.
<script type="text/javascript">
function ShowCurrentTime() {
$.ajax({
type: "POST", // Request type
url: "Jquery.aspx/GetCurrentTime", //Page URL/Method name
data: '{name: "' + $("#<%=txtUserName.ClientID%>")[0].value + '" }', // parameter
contentType: "application/json; charset=utf-8",
dataType: "json",
success: OnSuccess,//success method
failure: function (response) {
alert(response.d);
}
});
}
function OnSuccess(response) {
alert(response.d);
}
</script>
Below is our server side code. Note that this method is declared as static and a WebMethod
[System.Web.Services.WebMethod]
public static string GetCurrentTime(string name)
{
return "Hello " + name + Environment.NewLine + "The Current Time is: "
+ DateTime.Now.ToString();
}
public static string GetCurrentTime(string name)
{
return "Hello " + name + Environment.NewLine + "The Current Time is: "
+ DateTime.Now.ToString();
}
No comments:
Write comments