In this article I will explain with an example, how to call Code Behind function from Client Side (JavaScript) in ASP.Net using C# and VB.Net.
The Code Behind function can be called from Client Side (JavaScript) using ASP.Net AJAX PageMethods in ASP.Net.
Enabling PageMethods
The first thing you need to do is add a ASP.Net AJAX ScriptManager to the page and set its EnablePageMethods property to true.
<asp:ScriptManager ID="ScriptManager1" runat="server" EnablePageMethods="true">
HTML Markup
The following HTML Markup consists of an ASP.Net TextBox, an HTML Button and an ASP.Net AJAX ScriptManager.
<form id="form1" runat="server">
<asp:ScriptManager ID="ScriptManager1" runat="server" EnablePageMethods="true">
Your Name :
<asp:TextBox ID="txtUserName" runat="server" ></asp:TextBox>
<input id="btnGetTime" type="button" value="Show Current Time" onclick="ShowCurrentTime()"/>
Client Side Script
When user enter his name and Button is clicked the ShowCurrentTime JavaScript method is executed to get the Current Time.
The ShowCurrentTime method makes an AJAX call to the server using ASP.Net AJAX ScriptManager PageMethods and executes the GetCurrentTime method which accepts the username and returns a string value.
<script type="text/javascript">
    function ShowCurrentTime() {
        PageMethods.GetCurrentTime(document.getElementById("<%=txtUserName.ClientID%>").value, OnSuccess);
    function OnSuccess(response, userContext, methodName) {
The WebMethod
The following WebMethod returns a greeting message to the user along with the current server time. An important thing to note is that the method is declared as static (C#) and Shared (VB.Net) and is decorated with WebMethod attribute, unless you do this you won’t be able to call the methods using ASP.Net AJAX ScriptManager PageMethods.
public static string GetCurrentTime(string name)
    return "Hello " + name + Environment.NewLine + "The Current Time is: "
        + DateTime.Now.ToString();
<System.Web.Services.WebMethod()> _
Public Shared Function GetCurrentTime(ByVal name As String) As String
    Return "Hello " & name & Environment.NewLine & "The Current Time is: " & _
End Function
Call Code Behind function from Client Side (JavaScript) in ASP.Net
Browser Compatibility

The above code has been tested in the following browsers.

Internet Explorer  FireFox  Chrome  Safari  Opera 

* All browser logos displayed above are property of their respective owners.