Tuesday, 13 September 2011

How to call Webmethod using Javascript and JQuery in asp.net ?


//-- .Aspx Code
 <script src="jquery-1.6.2.js" type="text/javascript"></script>
 //---- Using Javascript -----
    <script type="text/javascript">
        function myServiceFun() {
            PageMethods.myWebMethods(webMethodSuccess, webMethodFail);
        }
        function webMethodSuccess(name) {
            alert(name);
        }
        function webMethodFail(myError) {
            alert(myError);
        }
    </script>
 //---- Using JQuery ----
    <script type="text/javascript">
        $(document).ready(function () {
            $("#btnJQuery").click(function () {
                $.ajax({
                    type: "POST",
                    url: "Default.aspx/myWebMethods",
                    data: "{}",
                    contentType: "application/json; charset=utf-8",
                    dataType: "json",
                    success: function (msg) {
                        AjaxSucceeded(msg);
                    },
                    error: AjaxFailed
                });
            });
        });

        function AjaxSucceeded(result) {
            if (result.d == true)
                alert(result.d);
            else
                alert(result.d);
        }

        function AjaxFailed(result) {
            alert(result.status + ' ' + result.statusText);
        }   
    </script>

   <asp:ScriptManager ID="ScriptManager1" runat="server" EnablePageMethods="true">
    </asp:ScriptManager>
    <input id="btnJS" type="button" value="JS-WebMethod" onclick="myServiceFun();" />
    <input id="btnJQuery" type="button" value="JQuery-WebMethod" />

//--- .cs code

 [WebMethod]
    public static string myWebMethods()
    {
        string str = "";
        SqlConnection con = new SqlConnection("Data Source=MyserverName;Initial Catalog=DBName;User  ID=Rajesh;Password=Rolen");
        SqlCommand cmd = new SqlCommand();
        SqlDataAdapter adp = new SqlDataAdapter();
        con.Open();
        cmd.Connection = con;
        cmd.CommandType = CommandType.Text;
        DataTable dt = new DataTable();
        cmd.CommandText = "select * from student order by NewId()";
        adp.SelectCommand = cmd;
        adp.Fill(dt);
        cmd.ExecuteNonQuery();
        str = dt.Rows[1]["stuname"].ToString();
        con.Close();
        return str;
    }

Note : If have any problem then set blow tag in web.config

<httpModules>
      <add name="ScriptModule" type="System.Web.Handlers.ScriptModule, System.Web.Extensions, Version=1.0.61025.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"/>
    </httpModules>

No comments:

Post a Comment