General_9
General_9

Reputation: 2319

Jquery ajax postback not hitting server method?

This is some of the code on the aspx page with the ajax post:

<div>
    Make Comment: <br />
    <textarea rows="7" cols="20" id="comment_content"></textarea><br />
    <input type="button" id="Make_Comment" value="Make Comment" />
</div>

<script type="text/javascript">
    $(document).ready(function () {
        $("#Make_Comment").click(function () {
            $.ajax({
                type: "POST",
                url: "Conversation.aspx/AddComment",
                data: '{ comment: This is a test comment via ajax postback }',
                contentType: "application/json; charset=utf-8",
                dataType: "json",
                success: function () {
                    alert("Got Back to code");
                }
            });
        });
    });
</script>

And here is the method I am trying to hit on the server side:

    [WebMethod]
    public static void AddComment(string data)
    {

    }

I have placed a breakpoint by the server side method but its not hitting it, what could be the issue?

Upvotes: 2

Views: 2231

Answers (2)

Suave Nti
Suave Nti

Reputation: 3747

Couple of things :

your data ina ajax call

  data: '{ comment: This is a test comment via ajax postback }'

should be

 data: "{'comment':'This is a test comment via ajax postback'}",

And your WebMethod :

 AddComment(string data)

Should be

 AddComment(string comment)

Upvotes: 2

Roger Medeiros
Roger Medeiros

Reputation: 813

Try this:

<script type="text/javascript">
$(document).ready(function () {
    $("#Make_Comment").click(function () {
        var comment = $("#comment_content").val();
        var Params = { comment : comment };
        $.ajax({
            type: "POST",
            url: "Conversation.aspx/AddComment",
            data: Params,
            contentType: "application/json; charset=utf-8",
            dataType: "json",
            success: function () {
                alert("Got Back to code");
            }
        });
    });
});
</script>

In your controller set the httppost.

[WebMethod]
[HttpPost]
public static void AddComment(string comment)
{

}

Upvotes: 1

Related Questions