ajaxmethods

jQuery ajax web method call


I am trying to call ajax web method when button is clicked. This is the following code I have written:

$(function() {
            $("<%=btnRatingSubmit.ClientID%>").click(function (e) {
                var textrating = $('#<%= btnRatingSubmit.ClientID %>');
                $.ajax({
                    type: 'POST',
                    url: 'NewRatings.aspx/SubmitRatings',
                    data: '{rating: \'' + textrating.val() + '\'}',
                    contentType: 'application/json; charset=utf-8',
                    dataType: 'json',
                    success: function doNothing(data) {
                    },
                    error: function throwError(data) {
                    },
                });
            });
            
            

This is asp button I am using:

 <asp:Button ID="btnBack" runat="server" Text="Back To Results" OnClick="btnBack_Click"  />

The code behind is

[WebMethod]
        [ScriptMethod]
        public static void SubmitRatings(string rating)
        {
            if (HttpContext.Current.Request.QueryString["ID"] != null)
            {
                if (HttpContext.Current.Session["LoginId"] != null)
                {
                    string str = HttpContext.Current.Request.Form["lblRate"];

                    RatingsBAL bal = new RatingsBAL();
                    bal.StoreRatings(HttpContext.Current.Session["LoginId"].ToString(), HttpContext.Current.Request.QueryString["ID"], Convert.ToInt32(rating));
                }
            }
        }

But for some reason the web method is not being fired. Can anyone help me please?


Solution

  • Change $("<%=btnRatingSubmit.ClientID%>").click to
    $('#'+"<%=btnRatingSubmit.ClientID%>").click

    You were missing a #, which is used to select elements by their ids in jquery.

    Full Code:

    $(function () {
        $('#' + "<%=btnRatingSubmit.ClientID%>").click(function (e) {
            var textrating = $('#<%= btnRatingSubmit.ClientID %>');
            $.ajax({
                type: 'POST',
                url: 'NewRatings.aspx/SubmitRatings',
                data: {
                    rating: textrating.val()
                },
                contentType: 'application/json; charset=utf-8',
                dataType: 'json',
                success: function doNothing(data) {},
                error: function throwError(data) {},
            });
        });