jQuery with ASP.NET

Building rich UI with jQuery and ASP.NET

Modules and AJAX Updates Every X Seconds

without comments


In this post I want to show you how easy you can achieve AJAX asynchronous updates with jQuery. Typical scenarios where such functionality is handy are all sorts of modules which you would like to update without reloading entire page like:

  • The latest tweeter updates
  • The latest comments
  • Currently logged in users, or number of users online
  • and so on …

In my example I will show you how to create module showing currently logged in users which will be updated asynchronously every 10 seconds.

1. Create ASP.NET Web Form Page which outputs JUST the module’s HTML

Here is ASP.NET code for my module:

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="CurrentlyLoggedInUsers.aspx.cs" Inherits="TestWebApp.Modules.CurrentlyLoggedInUsers" %>

<asp:Repeater ID="rptUsers" runat="server">
    <HeaderTemplate><div id="loggedInUsers"></HeaderTemplate>
    <ItemTemplate><a href="#"><%# Container.DataItem%></a>, </ItemTemplate>
    <FooterTemplate></div></FooterTemplate>
</asp:Repeater>

Generated at <%= DateTime.Now.ToLongTimeString() %>

And code behind code:

public partial class CurrentlyLoggedInUsers : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        // dummy list of users
        var list = new List<String> { "john", "mark", "james", "mike", "rodney" };

        rptUsers.DataSource = list;
        rptUsers.DataBind();

        // simulate real life scenario where it takes some time to generate the list
        Thread.Sleep(2000);
    }
}

As you can see it’s nothing sophisticated, very simple HTML, Repeater and dummy list of users. Good base to check how this solution works and to build on top of that later on…

2. Module and jQuery code

On other pages, where module is supposed to be located, it’s required to have only a div tag inside of which module will be loaded by jQuery:

<div id="LoggedInUsersModule"></div>
<div id="LoggedInUsersModuleUpdateStatus"></div>

Second div tag will be used to indicate that AJAX update is in progress and is loading new data. It’s not a part of core solution but I think it’s something which is nice to have. It improves user’s experience.

And now jQuery code:

$(document).ready(function () {
    updateLoggedInUsersModule();
    window.setInterval(updateLoggedInUsersModule, 10000)
});

function updateLoggedInUsersModule() {
    $('#LoggedInUsersModuleUpdateStatus').html('Loading ...').fadeIn('fast');
    $('#LoggedInUsersModule').load('/Modules/CurrentlyLoggedInUsers.aspx', function(response, status, xhr) {
        $('#LoggedInUsersModuleUpdateStatus').fadeOut('fast');
    });
}

Explanation:

  • First 4 lines a responsible for setup. In the second line I’m manually calling updateLoggedInUsersModule() function to load initial data. I don’t want to wait 10 seconds to show something on a page.
  • window.setInterval() function is a JavaScript’s built-in function which will call function passed as a first parameter (updateLoggedInUsersModule() in my case) every 10 seconds (second parameter)
  • In 7th line I’m updating status by setting new inner HTML and then jQuery function fadeIn() will display the element.
  • 8th line is the most important line, load() function will load data from server and place it into selected element. In our case that will be div with id LoggedInUsersModule.
  • Last parameter of load() function is a callback function which will be invoked after loading the data. I used this place to hide ‘Loading …’ text and this way show that operation has ended with success. Text will be hidden by fading them to transparent thanks to fadeOut() function.

What next?

  • Nice thing about load() function is that you don’t necessarily have to use entire HTML generated by server. You can use jQuery selectors on that HTML in a following way: $(‘#LoggedInUsersModule’).load(‘/Modules/CurrentlyLoggedInUsers.aspx #loggedInUsers‘)
  • Please remember that modules like this, with AJAX updates done every X seconds will be heavily used so it’s essential to make sure that performance is not a problem. Use a lot of caching on server-side if necessary.
VN:F [1.9.20_1166]
Rating: 9.5/10 (2 votes cast)
Modules and AJAX Updates Every X Seconds, 9.5 out of 10 based on 2 ratings

Written by admin

September 15th, 2010 at 9:06 pm

Leave a Reply