Oct 26 2006

Timed Ajax calls with JQuery and ASP.NET

Posted by admin under Ajax

This article is part of an article serie - please start by reading ASP.NET and JQuery - first example , JQuery and ASP.NET - lets involve ASP.NET  and Ajax loading animation with JQuery and ASP.NET .

Now this is an exact port of the case we solved using Ajax.NET in this article.

We want to periodically call our "timeserver" using Ajax calls and here's the ASPX and JavaScript needed:



<head runat="server">
    <title>Untitled Page</title>
</head>
<script src="jquery.js" type="text/javascript"></script>
<script type="text/javascript">
$(document).ready(function() {
     setTimeout(MyUpdate,10 * 1000);
});


   
function MyUpdate()
{
    $.get("ajaxdata.ashx",function(result)
        {
            if ( $('#lblMinute').text() != result )
            {
                $('#lblMinute').html(result);
                $('#lblMinute').fadeOut(450);
                $('#lblMinute').fadeIn(450);
                $('#lblMinute').fadeOut(450);
                $('#lblMinute').fadeIn(450);
                $('#lblMinute').fadeOut(450);
                $('#lblMinute').fadeIn(450);
            }
        });
    setTimeout(MyUpdate,10 * 1000);
 }
</script>
<body>
    <form id="form1" runat="server">
    <div>
    <span style="background-color:LightBlue" >Autoupdating every 10 seconds...</span>
    <table border="1">
    <tr>
    <td>Something</td>
    <td><asp:Label ID="lblDataUpdated" runat="server">Hello there bla bla</asp:Label></td>
    </tr>
    <tr>
    <td>Other important stuff</td>
    <td>Again more bla bla</td>
    </tr>
    <tr>
    <td>Current minute is</td>
    <td><asp:Label ID="lblMinute" runat="server"></asp:Label></td>
    </tr>
...
...

I still havn't gotten into jQuery that much, so it might be that a "real jquery developer" would laugh at this solution - however it did solve my problem and I am happy with that.

As you can see there is no PeriodicalUpdater or anything in JQuery  - we are using the regular setTimeout. I read in the JQuery mailing list  that the idea behind jQuery is to enhance the javascript where it's needed - and the setTimeout function is appearantly good enough. That way of thinking really make sense to me - and it makes me even more convinced there is a bright future for this library!

Attachments