Calling server-side script from AJAX

I am trying to call server-side script through javascript but I encounter following error,

PageMethods is undefined.

Please see attched file,

<%@ Page Language="VB" AutoEventWireup="false" CodeFile="Default.aspx.vb" Inherits="_Default" %>
<%@ Register Assembly="System.Web.Extensions, Version=1.0.61025.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"
    Namespace="System.Web.UI" TagPrefix="asp" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "">
<html xmlns="" >
<head runat="server">
    <title>Untitled Page</title>
<body onload="CallSum()" >
<form id="form1" runat="server">
   <asp:scriptmanager ID="Scriptmanager1" runat="server" EnablePageMethods="true"></asp:scriptmanager>
   <script language="javascript" type="text/javascript">
    function CallSum() 
        //Get the controls
        var txt1 = document.getElementById('box1');
        var txt2 = document.getElementById('box2');
        var txtresult = document.getElementById('answer');
        PageMethods.Sum(txt1.value, txt2.value, OnCallSumComplete, OnCallSumError, txtresult);
    function OnCallSumComplete(result,txtresult,methodName)
        //Show the result in txtresult
        txtresult.value = result;
    function OnCallSumError(error,userContext,methodName)
        if(error !== null) 
        <asp:TextBox ID="box1" runat="server" Style="z-index: 100; left: 144px; position: absolute;
            top: 120px">2</asp:TextBox>
        &nbsp; &nbsp;&nbsp;
        <asp:TextBox ID="box2" runat="server" Style="z-index: 101; left: 320px; position: absolute;
            top: 120px">5</asp:TextBox>
        <asp:TextBox ID="answer" runat="server" Style="z-index: 103; left: 264px; position: absolute;
            top: 200px"></asp:TextBox>
 Public Shared Function Sum(ByVal x As Integer, ByVal y As Integer) As Integer
        Return x + y
    End Function

Open in new window

Who is Participating?
wht1986Connect With a Mentor Commented:
Define the WebMethod attribute and it has to be marked static for the ScriptManager to see it

public partial class _Default : System.Web.UI.Page

  public static int Sum (int x, int y)
    return DateTime.Now.ToString();
siddiqishahidAuthor Commented:
Now I am getting the result but also I am getting javascript popup message and it says, "Permission denied"

It points to PageMethods line when I view the source. Any suggestions?

i think it has to do with calling CallSum from the onload event of the body.  Remove it from there, and place a simple <input type=button onclick="CallSum();" /> element on the page. Tell me if thatworks correctly.
siddiqishahidAuthor Commented:
Thanks for you help!!
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.