by Andrzej Kowal

Datatables.net – ajax pagination on scroll

Listing and paginating data in a web application can be implemented in many different ways. One technique I really like is automatic ajax pagination on window scroll. It provides great user experience and a clean UI without any paging controls. It requires loading just enough items to force the browser to show the vertical scrollbar. When user decides to scroll the window – more items are loaded with ajax as soon as the scroll reaches around 80% of the window height. This approach is widely used by many websites: Facebook, Twitter, Pinterest, LinkedIn and many more. However when it comes to tabular data plain old paging is still implemented quite often, Time for a change.

Recently, when working on insights feature in Ping.it, I had to implement “expand on scroll” behavior in an HTML table driven by jQuery datatables plugin. It is a very handy utility, which converts any HTML table into a powerful client-side enabled grid. It has two basic operation modes: client and server side. To my surprise in the server mode the grid cannot be easily extended with new rows loaded from the server. It supports only the traditional paging. When I tried to force the grid to load more rows, it ended up refreshing the whole grid. After a bit of research and experiments I came up with a solution. In the scroll event handler more data is loaded from the server with ajax:

[javascript]
var scrollForMoreData = function() {
$.ajax({
url: ‘/LoadMoreData’,
data: { … },
success: ajaxSuccess
});
};
[/javascript]

The server JSON response contains formatted HTML table rows:

[javascript]
var result = {
"content": "<tr>
<td>Mary Jane</td>
<td>26</td>
</tr>
<tr>
<td>Peter Parker</td>
<td>28</td>
</tr>…",
"hasMore": true
};
[/javascript]

On ajax success the <tr>s are simply appended to the end of the existing HTML table:

[javascript]
var ajaxSuccess = function (result) {
$(‘#my-table tbody’).append(result.content)
};
[/javascript]

The datatables sorting and filtering still can be used – in such case full grid refresh is the correct behavior (since sorting or filtering can fetch data currently not visible in the grid).

There is one important thing to consider – when loading more data with ajax it is essential to copy the datatable’s auto-generated ajax request data in order to send correct sorting and filtering parameters to the server:

[javascript]
$(‘#my-table’)
.on(‘xhr.dt’, function () {
var ajaxData = $(this).api().ajax.params();
$(this).data(‘custom-ajax-parameters’, ajaxData);
});
[/javascript]

Note that xhr event must be bound with the .dt namespace. Later when user scrolls the page I can retrieve the ajaxData object stored within the #my-table DOM object. And send this object as input to my “scroll” ajax request. This ensures that the server will actually return correctly sorted and filtered result. Since we don’t use datatables paging feature we need to handle it ourselves e.g. by adding additional parameter to “scroll” ajax request – the amount of already displayed rows (or page number, depending on your paging implementation). The adjusted scrollForMoreData function looks like this:

[javascript highlight=”2,3″]
var scrollForMoreData = function() {
var ajaxData = $(‘#my-table’).data(‘custom-ajax-parameters’);
ajaxData.skipRows = $(‘#my-table tbody tr’).length;
$.ajax({
url: ‘/LoadMoreData’,
data: ajaxData,
success: ajaxSuccess
});
};
[/javascript]

Happy data-listing!

by Andreas

Aborting AJAX requests in ASP.NET applications

imageI’ve been working on a pretty extensive web application lately, build on top of the .NET framework but with around 80% client side functionality (KnockoutJS, jQuery). There’s a lot of AJAX calls back to the server (naturally.. ) and one of the challenges I faced was that ASP.NET refused to navigate away from a page until all AJAX requests were processed. I did some searching and found out that an AJAX request could be aborted by adding some functionality to the window.onbeforeunload event:

window.onbeforeunload = function() {
    if (ajaxRequest !== undefined) {
        ajaxRequest.abort();
    }
};

 

By adding some logging to console I could clearly see that as soon as I clicked a link to navigate away this event was called and processed. But still nothing happened until the request had fully been processed – which made me think this had to do with the browser. Wrong assumption, and when writing this it seems very obvious to me why but then again retrospect is an ugly thing.

A bit more research and it turned out that this was all due to ASP.NET session state (which is enabled by default). Because of the session state my site serializes all requests within the same session, so the request for a new page would not be processed until the first one had completed. Turning session state off completely was out of the question, but by changing my .ashx handler (which receives all my ajax requests) to implement the IReadOnlySessionState interface rather than IRequiresSessionState there is no lock on the current session and concurrent requests are made possible.

Something to keep in mind though is that aborting an ajax request obviously doesn’t stop the server from processing it.

by Stian

Call ASP.NET AJAX page methods using jQuery

If you are used to working with MVC.NET and jQuery you might not want to start playing with the ScriptManager when you go back to writing an ASP.NET Web application again. Calling WebMethods using the ScriptManager will automatically add 100kb of Javascript to your page and will add three extra http requests per call! Of course, it is very simple to use, but so is the jQuery way as well, so if you are used to calling your actions directly with .ajax(), there is no reason not to .

To call ASP.NET page methods directly from jQuery without the need of a ScriptManager in your page, use the following:

Your jQuery code

   1:  var params = '{"firstname":"' + $("#firstname").val() + 
   2:               '", "lastname":"' + $("#lastname").val() + '"}';
   3:  $.ajax({
   4:      type: "POST",
   5:       url: "Default.aspx/SavePerson",
   6:       data: params,
   7:        contentType: "application/json; charset=utf-8",
   8:        dataType: "json",
   9:        success: function (msg) {
  10:            alert(msg.d)                      
  11:        }
  12:  });

Your serverside code

   1:  [WebMethod]
   2:  public static string SavePerson(string firstname, string lastename)
   3:  {
   4:      //do saving or wheatever
   5:      return "Some message back to client";
   6:  }

 

If you’re already using the ScriptManager for other purposes, there’s no harm in using its JavaScript proxy to call your page methods. However, if you aren’t using a ScriptManager or have already included jQuery on your page, I think it makes sense to use the more efficient jQuery method.

by Degree Admin

Hva er nytt i Sharepoint 2010?

  • Stor oppdaterting av grensesnittet. Sharepoint benytter nå “Ribbons”. Hensikten er at Sharepoint skal bli så likt som andre Office applikasjoner som mulig.
  • Utvidede muligheter på “mysite”. Funksjoner som: Du kan se hva brukeren driver med, chatte, skrive meldinger og få oversikt over hvor brukeren plasserer seg i organisasjonen og blant de andre brukerne.
  • Bedre støtte for andre nettlesere. Microsoft har bygget opp denne funksjonaliteten med Ajax og ikke ActiveX.
  • Metadata er enklere å navigere i enn før. Du kan legge til nøkkelord, og navigere i disse via et hiarki som likner mapper. Dette, sammen med en unik id som følger dokumentet gjennom hele systemet, skal gjøre dem lettere å finne.
  • Bedre søk. Boolske parametre, fonetisk søk og rangering av søkeresultater er nå inkludert.
  • Fast Search for Sharepoint. Søkeserver i systemet gir Sharepoint smartere søk, med blant annet forhåndsvisninger, nøkkelord-forslag og forståelse for lingvistikk.
  • Enklere å lage sine egne “dashboards”; en slags hovedside for Sharepoint-brukerne. Før krevde dette koding. Nå er det mulig ved å dra og slippe elementer i en “dashboard-designer”.
  • Sharepoint 2010 inneholder også noe som heter Composites. Du kan via Sharepoint åpne for eksempel sql-databaser fra andre systemer. Du kan dermed endre og lagre dem i Sharepoint, og databasene oppdaterer seg. Sharepoint fungerer med andre ord som en redigerer for filer som kanskje kjører på andre eldre og mer kompliserte systemer.
  • “Embed” Excel dynamiske grafer. Grafer fra Excel vil holde seg oppdatert på siden.
  • Bedre lister. Mulighet for millioner av elementer i lister.
  • Business Connectivity Services. Interaksjon  med eksterne data på samme måte som SharePoint data.
  • Mickroblogging. Man kan lage egen blogg på egne områder eller for bedriften.
  • Støtte for content types på tvers av Site Collection, Web Applications, Farms og Multiple Farms.
  • Enterprise Content Management (ECM). Forbedring av dokumenthåndteringsystem. Mange nye funksjoner og større muligheter, både for brukere, administratorer, og utviklere. Unike dokument-ID`er, Document sets, taksonomi, metadata services og enda bedre Office integrasjon.
  • Arbeidsflyt har fått mange nye funksjoner. Designer arbeidsflyt kan bli pakket som en  .wsp fil for utrulling på andre sider. Både arbeidsflyt på sites og lister. Kan opprette arbeidsflyt i Visio. Kan også eksportere det ut i Sharepoint Designer for deretter å importere det inn til Visio igjen.
  • Visio services in SharePoint 2010. Visio 2010 har fått bedret funksjonalitet for å koble visio-diagrammer og figurer mot en eller flere datakilder. Visio services er en måte å dele disse diagrammene vha en browser – brukerne trenger ikke Visio-klienten.