Xaisoft
Xaisoft

Reputation: 46591

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?

Upvotes: 1

Views: 556

Answers (2)

Tomas Aschan
Tomas Aschan

Reputation: 60564

karim79's solution will do the job in Internet Explorer - but to make sure that it works in Firefox and other browsers as well, you probably want to add an input argument to the click handler that will take the click event, and stop the event.

$("#btnGetDate").click(function(ev) {
    ev.stopPropagation();
    $.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;
});

Upvotes: 1

karim79
karim79

Reputation: 342635

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;
    });

Upvotes: 3

Related Questions