I am using the following code to get time from the server.
The btnNoP .click function returns the proper time, however the asp:Button returns alert Error on page.
How can i successfully call a webmethod from document.ready when a asp:button is clicked?
-
<script type="text/javascript"> function PageMethod(fn, paramArray, successFn, errorFn) { var pagePath = window.location.pathname; //Create list of parameters in the form : {"paramName1":"paramValue1","paramName2":"paramValue2"} var paramList = ''; if (paramArray.length > 0) { for (var i=0; i<paramArray.length; i+=2) { if (paramList.length > 0) paramList += ','; paramList += '"' + paramArray[i] + '":"' + paramArray[i+1] + '"'; } } paramList = '{' + paramList + '}'; alert(pagePath + "/" + fn); //Call the page method $.ajax({ type: "POST", url: pagePath + "/" + fn, contentType: "application/json; charset=utf-8", data: paramList, dataType: "json", success: successFn, error: errorFn }); } function AjaxSucceeded (result) { alert(result.d); //$("#Result").text("Result : " + result.d); } function AjaxFailed (result) { alert("Error on Page"); } $(document).ready(function() { $('#btnNoP').click(function() { PageMethod("GetTime", [], AjaxSucceeded, AjaxFailed); }); $('#btnNoParams').click(function() { PageMethod("GetTime", [], AjaxSucceeded, AjaxFailed); }); }); </script> -
<asp:ScriptManager ID="sm" EnablePageMethods="true" EnablePartialRendering="true" runat="server"></asp:ScriptManager> <asp:Button ID="btnNoParams" Text="Get Time" runat="server" /> <input type="button" id="btnNoP" /> -
[WebMethod(true)] public static string GetTime() { return "You called at : " + DateTime.Now.ToShortDateString() + "-" + DateTime.Now.ToShortTimeString(); }
change the code as below.
or
following link may helpful
http://cmsnsoftware.blogspot.com/2011/01/how-to-call-csharp-function-in-ajax.html
Edit :-
if you are using jQuery ajax, you don’t need to add script manager in your page. And if you are adding script manager to page, you can directly call web method without jQuery. see the above link which describe how to access web method using JavaScript,jQuery and asp.net ajax.