[Solved] Call Server Side function from JavaScript Error: PageMethods is undefined

Last Reply one month ago By dharmendr

Posted one month ago

I have used the VB code for Call Server Side function from JavaScript without PostBack in ASP.Net in the link.

As in the code below. Unfortunately nothing happens when hit "Show Current Time".

JavaScript runtime error: 'PageMethods' is undefined

Please help me to find the error in my code.

<%@ Page Title="Test" Language="VB" AutoEventWireup="false" CodeFile="VB.aspx.vb" Inherits="VB" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
    <head id="Head1" runat="server">  
        <title>Test Page</title>  
    </head> 
    <body style = "font-family:Arial; font-size:10pt">
        <form id="form1" runat="server">
            <asp:ScriptManager ID="ScriptManager1" runat="server" EnablePageMethods="true">
            </asp:ScriptManager>
                <div>
                    Your Name :
                    <asp:TextBox ID="txtUserName" runat="server" ></asp:TextBox>
                    <input id="btnGetTime" type="button" value="Show Current Time" onclick="ShowCurrentTime()"/>
                </div>
        </form>
    </body>
</html>

<script type="text/javascript" language="javascript">
    function ShowCurrentTime() {
        PageMethods.GetCurrentTime(document.getElementById("<%=txtUserName.ClientID%>").value, OnSuccess);
    }
    function OnSuccess(response, userContext, methodName) {
        alert(response);
    }
</script> 

 

Partial Class VB
    Inherits System.Web.UI.Page

    Public Shared Function GetCurrentTime(ByVal name As String) As String
        Return "Hello " & name & Environment.NewLine & "The Current Time is: " & _
            DateTime.Now.ToString()
    End Function

    Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
    End Sub
End Class

 

Posted one month ago

Hi MEA,

You are missing WebMethod attribute for GetCurrentTime method.

MEA says:
 Public Shared Function GetCurrentTime(ByVal name As String) As String
        Return "Hello " & name & Environment.NewLine & "The Current Time is: " & _
            DateTime.Now.ToString()
    End Function

Change with below.

<Services.WebMethod()> ' this attribute is missing
Public Shared Function GetCurrentTime(ByVal name As String) As String
    Return "Hello " & name & Environment.NewLine & "The Current Time is: " & _
           DateTime.Now.ToString()
End Function