Rani Radcliff
Rani Radcliff

Reputation: 5084

Calling Function in Codebehind of aspx from Javascript Throws Error

I'm trying to call a function in the codebehind of my .aspx page once the window is fully displayed. I tried using:

    <script type="text/javascript">
    $(document).ready(function () {
        PageMethods.CheckForPageChange();
    });
</script>

And it throws the following error:

0x800a1391 - JavaScript runtime error: '$' is undefined

I was able to get window.onload to display an alert box, so I tried using it like this:

    <script type="text/javascript">
    window.onload = function () {
        PageMethods.CheckForPageChange();
    }
</script>

But it throws the error "PageMethods is undefined".

I have this inside of a "form" tag:

        <asp:ScriptManager runat="server" ID="ScriptManager1" EnablePageMethods="true"></asp:ScriptManager>

And this in my codebehind:

    [WebMethod]
    public void CheckForPageChange()
    {
        throw new NotImplementedException();
    }

Can someone please tell me what I am missing here? Any assistance is greatly appreciated!

Upvotes: 0

Views: 536

Answers (2)

Tarek Abdel Maqsoud
Tarek Abdel Maqsoud

Reputation: 58

0x800a1391 - JavaScript runtime error: '$' is undefined

Make sure that the JQuery has been loaded successfully.

it throws the error "PageMethods is undefined".

1- You have to make your server side method as a static method looks like this

[WebMethod]
public static void CheckForPageChange()
{
    throw new NotImplementedException();
}

2- Call the serverside method like that

<script type="text/javascript">
function OnSuccess(response){
   //Do Stuff
}
function OnError(error){
   //Do Other Stuff
}
$(document).ready(function () {
    PageMethods.CheckForPageChange(OnSuccess, OnError);
});

3- put your script outside <asp:ScriptManager>, put it in a separate <script> tag

Upvotes: 1

Zorken17
Zorken17

Reputation: 1896

The reason for the first error is that you do not include jQuery in your aspx page.

The next error properly is because you do not have runat="server". Try to modify your ScriptManagerlike this:

<asp:ScriptManager ID="ScriptManagerMain"
        runat="server"
        EnablePageMethods="true" 
        ScriptMode="Release" 
        LoadScriptsBeforeUI="true">
</asp:ScriptManager>

Upvotes: 0

Related Questions