Search code examples
javascriptasp.netserver-sidenanpagemethods

javascript returns NaN when calling server side function


I have the following javascript code that is trying to call a server side function:

    function server_GetStats(nodeID) {
        var result = PageMethods.getStats(nodeID);
        return result;
    }

    setInterval(function () {
        newVal = parseInt(server_GetStats(1089)) + parseInt(server_GetStats(1090));
        rate = (newVal - val) / (pollTime / updateCounterTime);
    }, pollTime);

And this is the server side function that is being called:

    [WebMethod]
    public static int getStats(object nodeID)
    {
        int stat= 0;
        SqlConnection conn = new SqlConnection();
        string connStr = ConfigurationManager.ConnectionStrings["ApplicationServices"].ToString();
        conn.ConnectionString = connStr;
        conn.Open();

        string sql = "SELECT stat FROM NODE_PROPERTIES WHERE NodeID = " + Int32.Parse(nodeID.ToString());
        SqlCommand cmd = new SqlCommand(sql, conn);

        stat = Int32.Parse((cmd.ExecuteScalar().ToString()));
        conn.Close();
        return stat;
    }

I've added asp:ScriptManager to the aspx page as well. Can't for the life of me figure out why I'm getting NaN. I checked that the SQL statement is OK too. Could someone shed some light on what I'm doing wrong?

Answer:

As was suggested I added a callback function. Ended up looking something like this:

    setInterval(function () {
        newVal = 0;
        server_GetStats(1089, 1090);
    }, pollTime);

    function server_GetStats(nodeID) {
        PageMethods.getStats(nodeID, OnGetStatsSuccess, OnGetStatsFailure);
    }

    function OnGetStatsSuccess(result) {
        newVal = parseInt(result);
        rate = (newVal - val) / (pollTime / updateCounterTime);
    }

    function OnGetStatsFailure(result) {
        //do something when your server-side function fails to return the desired value
    }

Code-behind stayed the same.


Solution

  • When you are calling a PageMethod, it is getting called asynchronously. That means, when you call server_GetStats(1089), it is returning from that function before the PageMethod even completes. To get your code to work, you'll need to define a callback for your PageMethod call. Something along these lines:

    var values = 0;
    
    function myCallback(result) {
        values += parseInt(result);
    
        // Maybe call a function here that notifies/changes the UI.
    }
    
    function server_GetStats(nodeID) {
        PageMethods.getStats(nodeID, myCallback);
    }
    

    Reference: http://www.geekzilla.co.uk/View30F417D1-8E5B-4C03-99EB-379F167F26B6.htm