Montag, Februar 15, 2016

Time to rethink the AjaxEngine

Technorati Tags:
The HTML world is about to step into a new era. A step that was prepared long ago. Everyone can see that the browser will be the home of more modern applications, responsive games, interactive media and enriched content.

The AjaxEngine in contrast was staying there for more than 5 years with almost no change even still many people use it or parts of it. During the last years buxes where fixed and adopting new browsers was implemented by changing as few as possible.

But time has changed:

  • The main driver is HTML version 5 standard (HTML5) that is broadly excepted and implemented in almost all the browsers almost completely.
  • HTML5 and the HTML predecessors have a long history since W3C started more than 20 years ago.
  • On 28. of October 2014 the HTML5 standard was pushed in the state of a recommendation (HTML 4.01 was in 1999) and the great companies Apple, Google and Microsoft have been involved and accepted.
  • When using the latest browser version HTML5 is running fine and only some features still are not x-browser compatible.
  • All the internert browser applications have changed their update strategy from yearly releases to continuous improvements.
  • Along with the core HTML5 standard further and complementary technologies have been developed.

There have been a lot of confusing standard discussions around. Many IT-religious questions have been discussed and quasi standards where published on various web-sides. Now that seems to be over. And more than just a standard agreement I see that it gets implemented in a serious and reliable way.

Applause to that great work !
... because it makes my life an an web developer easier than before !

You will see things going on in the AjaxEngine and old implementation approaches will be replaced. You can see thins on my web site but I will also release a version on Github and will drop supporting

Donnerstag, November 14, 2013

AjaxEngine: get rid of event.srcElement

It’s time to say goodbye to some of the compatibility tricks in the AjaxEngine. Here is the first article on maintaining your Javascript code if you come from some older versions.

A note for the future

If time is beyond April 2014 (the time when Windows XP and IE 8 and older dies), you don’t need to read and understand. If you find a code that reads obj.srcElement, just change it to
You stumbled upon some old-browser-compatibility issue.


The srcElement property on event objects was introduced by Microsoft to find out what html element was actually meant when a event was fired. The AjaxEngine then implemented some tricky code to make this property available in other browser too:

  // enable using evt.srcElement in Mozilla/Firefox
  Event.prototype.__defineGetter__("srcElement", function () {
    var node =;
    while (node.nodeType != 1) node = node.parentNode;
    // test this:
    if (node != alert("Unexpected!")
    return node;

Now, the W3C standard defines a target property that has the same meaning and also Microsoft moves to use the standard conform property in the newer browsers. I strongly advise to not support these older browsers any more because they never will be fixed for security issues any more.

For now you should find the target object inside an event handler by using:

var obj = || evt.srcElement;

and starting with April 2014 you just should use:

var obj =;

Changes to AjaxEngine

I searched all “.srcElement” occurrences and changed them to the compatible assignment

var obj = || evt.srcElement;
An updated download archive is available as well as commits to the sourcecode repository:
or directly using subversion:
See also

Samstag, Dezember 05, 2009

How to read cookie values in JavaScript

I recently had some odd effects with some pages that use cookies to store some local information. The bug seems to be widely spread in many web applications so here are my findings:

To read the value of a specific cookie that was set previously you have to analyze the string in document.cookie that contains all cookies. It’s a very readable format and looks like:

a=a101; aha=aha101; bob=bob101; b=b101; c01=c0101

The trick is to find the right cookie in this string and extract the value.

I used a JavaScript function, named getCookie() that searched for the position of the cookie name by using

start = document.cookie.indexOf(name + "=");

… and this is wrong in some cases.

If you search for the cookie named "b" in the sample above you will get a starting-position within the cookie named "bob" because the indexOf function stops at the first occurrence of the text "b=".

This seems to be a very common approach and some educational web sites still publish this kind of code that contains the mistake.

It’s easy to fix this line by including the space character:

var start = document.cookie.indexOf(" " + name + "=");
if (start >= 0) {
  start += 1
} else if (document.cookie.indexOf(name + "=") == 0) {
  start = 0;
} // if

But there is a more elegant solution when using regular expressions and even the retrieval of the value gets easier that I found at

Here is the full function:

function get_cookie (cookie_name)
  var results = document.cookie.match('(^;) ?' + cookie_name + '=([^;]*)(;$)');
  if (results)
    return (unescape(results[2]));
    return (null);

Check your code.

Samstag, November 15, 2008

Extending the initialization sequence of JavaScript behaviors

This topic was recently discussed in the OpenAjax group and here is the implemented solution for the AjaxEngine framework. The consensus was to solve the initialization problem on the application level and not within the OpenAjax hub.


When multiple components resist side by side on the same page the initialization sequence of the components can become critical for the page to work as expected. Therefore the JavaScript behavior mechanism supports 3 phases of initializing the application when a page loads:

  1. The optional init() method is called first for every control that was initialized by LoadBehavior. This method should contain all initialization code that puts the control in a fully working state. Especially the control should register for any interesting OpenAjax event.
  2. The optional initstate() method is called then and allows the control to inform other controls about their existence and publish state information by using OpenAjax events or direct method calls if appropriate.
  3. The optional afterinit() method is called at last to controls can finish the setup where all other controls are also working.

All controls can participate in the initialization phases by implementing the calls. They are all optional. All 3 methods will be called when the onload event is raised for the window object.

The term method

Another method named "term" can be defined in the JavaScript prototypes to implement a method that is called just before a page unloads. There is a real need for implementing code just before all HTML and JavaScript objects are thrown away in Microsoft Internet Explorer, because there is a well known problem with the memory management used by the HTML DOM and JavaScript. Both object libraries do have their own garbage collector implementation and in some cases circular references between objects of both worlds are not properly detected and memory will not get freed and useless memory consumption is the unwanted result.

The best solution against this “design weakness” is to set all references of JavaScript variables to HTML elements to null in this method.

There is also a great tool and some more background information available that helps to detect this kind of memory leak named Drip available at and is a definitive TO-DO when supporting older browser versions of IE.

Montag, Juli 07, 2008

How to set up a web project using the AjaxEngine – Part 1b

Some days ago I posted part 1a - a short instruction about how to set up a minimal project.

The sample I used to demonstrate that the infrastructure works was as simple as possible and is using a RPC style of Ajax calls to the server. Some topics have not been touched so here they come.

How to get the files

The easiest way to get all the files I’ve talked about is to go get them directly from the repository hosted as sourceforge. is the projects's home page and you can browse the repository directly by using the url

Here all the development progress will be available as soon as soon as I write about it.

Another possible way to get the files is to use a subversion client for example that includes more functionality like getting a copy of all the current files at once, looking into the change log and comparing different versions of the same file.

From time to time the download archives are updated too. You can find them on my site at

Calling web services the right way

I have to mention, that this is not the best way of calling a server because synchronous calls may block or freeze the client during the call and the call time may be very long when the network or the server is used a lot. Using asynchronous calls is the answer to that problem and there is simple but great mechanism inside the ajax.js file that makes asynchronous programming quiet easy. Here is just a brief explanation of how to use it. More of the mechanism and it's options can be found in the book Aspects of Ajax.

The typical AJAX scenario follows the following pattern and can be split into 4 separate problems:

  1. Waiting for an event that will start the Ajax call to the server.
    Sometime that’s an easy thing to do, because there is a button clicked and we just can attach the initializing code to an event. But sometimes events have to be queued up to avoid a race condition and get wrong answers.
  2. Collecting some data on the client side.
    It is often necessary to do this right before you call the server and not in the moment when the call is initiated.
  3. Communication with the server.
    That is done by using the client stub that is generated for each SOAP based web service.
  4. Finally using the result from the server.
    That must be done, when the data is available and is the typical asynchronous functionality of Ajax.

Many grown-up Ajax implementations are using a JavaScript object that binds the JavaScript functions that all together will solve the scenario and so does the AjaxEngine:

// declare an AJAX action var action1 = { // the prepare function collects and returns the data for the server side method.

// It just returns an array with the parameters and marks it with "multi". prepare: function(obj) { var p = []; p[0] = document.getElementById("n1").value; p[1] = document.getElementById("n2").value; p.multi = true; // the hint for the ajax Engine return (p); }, // the call element points to the proxy for the server call as usual call: proxies.CalcService.AddInteger, // the result will be written it into the appropriate html field. finish: function (p) { document.getElementById("outputField").value = p; } } // action1

This action can be used to start an Ajax call by using some inline code like this:

<input id="n1" onkeyup="ajax.Start(action1)" />

Now Ajax starts getting robust enough in a real web application.

The code is from the sample that you can find in the sample at

Sonntag, Juli 06, 2008

Calling WCF and SOAP based webservices from AJAX

The JavaScript proxy that is implemented for the Ajax engine to call SOAP based web services has been used on the ASP.NET platform for a long time and was ported to other platforms like Java. Some derived work can also be found for PHP and the Qooxdoo. It’s pretty stable for a while and that’s a good message.

When working with some specific Java based platforms there was a specific problem with the automatic generated WSDL descriptions, because they use an external schema for defining the structure of the passed data:

<wsdl:types> <xsd:schema targetNamespace=""> <xsd:import schemaLocation=http://localhost/AJAXEngine/S02_AJAXCoreSamples/CalcFactors.svc?xsd=xsd0

namespace="" /> ... </xsd:schema> </wsdl:types>

The workaround was to write the JSON structure that is used by the JavaScript proxy by hand (and that is still a good idea for high trafic web sites).

When adopting the WCF .svc services this kind of using WSDL and XML schema definitions can be found too.

A solution for this is quiet simple and can now be found in the wsdl.xslt and the GetJavaScriptProxy.aspx files.


The WSDL to JavaScript transformation now looks for import nodes under the wsdl:types and then imports the referenced schema by using the xslt document() function. Then this imported document is searched for the right element and the parameter and return value description is generated through the soapElem template. Here is the added xslt code:

<xsl:when test="/wsdl:definitions/wsdl:types/s:schema/s:import">

<!-- importing an external schema –>

<xsl:variable name="inputElementName" select="substring-after(wsdl:part/@element, ':')" />

<xsl:for-each select="/wsdl:definitions/wsdl:types/s:schema/s:import">

<xsl:variable name="doc" select="document(@schemaLocation)"/>

<xsl:for-each select="$doc/s:schema/s:element[@name=$inputElementName]//s:element">

<xsl:call-template name="soapElem">

<xsl:with-param name="name" select="@name" />

<xsl:with-param name="type" select="@type" />


<xsl:if test="position()!=last()">,</xsl:if>





In the .NET environment the document function will not work for security reasons without some special instructions for the xslt transform. When passing a  XmlUrlResolver when loading the xslt file the document() function can retrieve the referenced external document.

XmlUrlResolver resolver = new XmlUrlResolver();
resolver.Credentials = CredentialCache.DefaultCredentials;

XslCompiledTransform xsl = new XslCompiledTransform();
xsl.Load(Server.MapPath("~/ajaxcore/wsdl.xslt"), XsltSettings.TrustedXslt, resolver);

Implementing a WCF service for Ajax

Implementing a WCF service for Ajax is almost as simple as programming an *.asmx based service but you can also use an external C# class or interface for implementing the service.

You can find a sample source code in:

The configuration

By default the WCF services use the SOAP 1.2 format but we don’t need the ws-* functionality and the soap basic profile is perfect for using webservice with AJAX solutions. This can be done by using the following configuration in web.config:

      <behavior name="AjaxBehavior">
        <serviceMetadata httpGetEnabled="true" />
        <serviceDebug includeExceptionDetailInFaults="false" />

    <service behaviorConfiguration="AjaxBehavior" name="CalcFactors">
      <endpoint address="" binding="basicHttpBinding" contract="CalcFactors" />

Sonntag, Juni 22, 2008

How to setup a new AjaxEngine web project

I was asked how to setup a web project that uses the AjaxEngine so here is step by step tutorial for a minimal Ajax web project that calls a server side web service:

1. Create a new web project (I prefer using c#) or use your existing web project.

I started with a new project and named it "mini". There is nothing special that you have to set up. It even works without a web.config.

2. Copy the ajaxcore folder to your project.

You can find this folder and the files on sourceforge
in the subversion repository by using the path
or in one of the source code downloads like

For this project you only need the following core files
ajax.js: the client side AjaxEngine

GetJavaScriptProxy.aspx: the JavaScript proxy generator
wsdl.xslt: the WSDL to JavaScript transformation


That’s all you have to do to prepare the web project to use the core part of the AjaxEngine. I suggest you use the ajaxcore folder

3. Create a folder named "/calc"

This folder will contain the minimal web application by using a web form and a web service.

I guess you don't implement pages in the root folder of your web application so I follow this best practice here too.

4. Implement a service /calc/WebService1.asmx

There is only one method we need so here is some c# code:

using System.ComponentModel;
using System.Web;
using System.Web.Services;
using System.Web.Services.Protocols;

namespace mini.calc {
  /// Summary description for WebService1
  [WebService(Namespace = "")]
  [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
  // To allow this Web Service to be called from script, using ASP.NET AJAX, uncomment the following line. 
  // [System.Web.Script.Services.ScriptService]
  public class WebService1 : System.Web.Services.WebService {

    public double Add(double sum1, double sum2) {
      return (sum1 + sum2);

5. Create a new page named WebForm1.aspx in the calc folder

I just use the new item wizard from visual Studio to do this so the typical elements are there already.
There is not much code that must be put into this file.

6. include the ajax.js:

<script src="../ajaxcore/ajax.js" type="text/javascript"></script>

The ajax.js file reference should be included in the <head> element.

7. include the proxy for the webservice:

<script src="../ajaxcore/GetJavaScriptProxy.aspx?service=/calc/WebService1.asmx" type="text/javascript"></script>

This script include should also be included in the <head> element and will make the just implemented webservice and webmethod available through the JavaScript object proxies.WebService1.Add.

8. Implement the User interface

A minimalist UI means just 3 fields and some text.
You also have to remove the <form> element because the fields are not used to post data to the server. 

<input id="sum1" type="text" /> + <input id="sum2" type="text" /> = <input id="result" type="text" />

9. Implement the JavaScript code

This is the trickiest part of it, but it's simple too:
A timer is used to call a function every 200 milliseconds that checks for some changed input values.
The web service is called if any value has changed.

<script type="text/javascript">
  var sum1_obj = document.getElementById("sum1");
  var sum2_obj = document.getElementById("sum2");
  var result_obj = document.getElementById("result");
  var sum1_val = "";
  var sum2_val = "";

  window.setInterval(window.checkValues, 200);
  function checkValues() {
    if ((sum1_obj.value != sum1_val) || (sum2_obj.value != sum2_val)) {
      sum1_val = sum1_obj.value;
      sum2_val = sum2_obj.value;
      result_obj.value = proxies.WebService1.Add(sum1_val, sum2_val);
    } // if
  } // checkValues

10. And that's all

Start the Web Form and see how it works.