Thursday 4 December 2014

Call web method from page using jquery and ajax without postback

Introduction: In this article I will show you how to call webmethod from aspx page using jquery
and ajax without postback.

Description:  Call webmethod from aspx page using jquery and ajax without postback.



In Aspx Page:

<head runat="server">
    <title></title>
<script src="scripts/jquery-1.3.2.min.js" type="text/javascript"></script>
<script type = "text/javascript">
function ShowTime() {
    $.ajax({
        type: "POST",
        url: "CS.aspx/GetTime",
        data: '{name: "' + $("#<%=txtName.ClientID%>")[0].value + '" }',
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        success: OnSuccess,
        failure: function(response) {
            alert(response.d);
        }
    });
}
function OnSuccess(response) {
    alert(response.d);
}
</script>
</head>

<body style = "font-family:Arial; font-size:10pt">
<form id="form1" runat="server">
<div>
Your Name :
<asp:TextBox ID="txtName" runat="server"></asp:TextBox>
<input id="btnGetTime" type="button" value="Show Current Time"
    onclick = "ShowCurrentTime()" />
</div>
</form>
</body>


In Code Behind:

[System.Web.Services.WebMethod]
public static string GetCurrentTime(string name)
{
    return "Hello " + name + Environment.NewLine + "The Current Time is: "
        + DateTime.Now.ToString();
}


No comments:

Post a Comment