views:

189

answers:

3

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?

+3  A: 

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;
    });
karim79
I thought about this, but I am not sure where to add the return false;
Xaisoft
@Xaisoft - see my edit.
karim79
Great, That did it. Thanks.
Xaisoft
+1  A: 

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;
});
Tomas Lycken
It actually worked in firefox, but your idea is also good.
Xaisoft
A: 

I can't get this to work.