Search code examples
asp.netjquerypagemethods

Why does this JQuery call to asp.net pagemethod load the whole page?


Here is a snippet of my html:

<input id="btnGetDate" type="submit" value="Get Date" />
    <div id="Result"></div>

<script type="text/javascript">

    $(document).ready(function() {

        $("#btnGetDate").click(function() {
            $.ajax({
                type: "POST",
                url: "Date.aspx/GetDate",
                data: "{}",
                contentType: "application/json; charset=utf-8",
                dataType: "json",
                success: function(msg) {
                    $("#Result").text(msg.d);
                }
            });
        });
    });

</script>

My Page Method id defined as follows:

    [System.Web.Services.WebMethod]
    public static string GetDate()
    {
        return DateTime.Now.ToString();
    }

When I click the Get Date button, I saw the date flash on the screen for a second, but since the whole page is loading, it disappears and when I view it in firebug, I see it is doing the POST, but quickly disappearing. Any ideas on how to resolve this?


Solution

  • Try returning false from your $("#btnGetDate").click() event handler:

        $("#btnGetDate").click(function() {
            $.ajax({
                type: "POST",
                url: "Date.aspx/GetDate",
                data: "{}",
                contentType: "application/json; charset=utf-8",
                dataType: "json",
                success: function(msg) {
                    $("#Result").text(msg.d);
                }
            });
            return false;
        });