Question

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?

Was it helpful?

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

OTHER TIPS

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;
});
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top