Wednesday, August 25, 2010

How to update small portion of a website using jQuery and ajax

We can use Generic Hanlder to render the response for the ajax request.
Example

Page
<%@ Page Language="C#" %>
<html xmlns="http://www.w3.org/1999/xhtml">
<head id="Head2" runat="server">
    <script src="Scripts/jquery-1.4.1.min.js" type="text/javascript"></script>
    <script language="javascript" type="text/javascript">
            function UpdateTime() {                
                $.ajax({
                    url: "GenericHandler.ashx",
                    success: function (data) {
                        $(".LabelTime").text(data);
                    }
                });
            }
 
            $(document).ready(function () {
                setInterval('UpdateTime()', 3000);
            });
    </script>
    <script runat="server">        
        protected override void OnLoad(EventArgs e)
        {
            base.OnLoad(e);
            this.lblTime.Text = DateTime.Now.ToString("hh:mm:ss");
        }
    </script>
</head>
<body>
    <form id="form1" runat="server">
        <asp:Label runat="server" ID="lblTime" CssClass="LabelTime" />
    </form>
</body>
</html>
GenericHandler.ashx
public class GenericHandler : IHttpHandler
{
    public void ProcessRequest(HttpContext context)
    {            
        context.Response.Write(DateTime.Now.ToString("hh:mm:ss"));
        context.Response.Flush();
        context.Response.End();
    }
 
    public bool IsReusable
    {
        get
        {
            return false;
        }
    }
}

No comments:

iPhone Launch Screen Sizes

iPhone Portrait iOS 8 Retina HT 5.5 = 1242 X 2208 Retna HD 4.7 = 750 X 1134 iPhone Landscape iOS 8 Retina HD 5.5  2208 X 1242 iPho...