SCRIPTING:

Sophia Vergara
THE MOST ELEGANT AJAX CLASS EVER: CREATE COEXISTING MULTIPLE AJAX INSTANCES BY CURRYING, DELIVER MULTIPLE ASYNCHRONOUS XMLHTTP GET POST OR HEAD REQUESTS, USE ONE SINGLE CLASS WRAPPER FOR ALL
Not necessarily the best or the most complete Ajax class, but a very elegant one maybe. The fact it includes only the basic functionality is actually a feature, because its code is so neat and it is so flexible, that adding custom properties may be just fun. It is a class that allows you to initialize as many instances as you prefer, with one unique class wrapper, and a nice way to define further echo handlers.
August 2006
{ @ }
The model above is Sophia Vergara
LOADS OF SOPHIA VERGARA ON THE NET
topleftpixel.com

FEATURES OF THE CLASS
What this class has that may make it interesting
This file can't be as detailed (or boring, you decide) as my documentation normally is. This happens both because of time reasons, and because if you never heard before about Ajax (a way to query a file on a server via JavaScript, or evan check a database via Javascript using a file on a server as the proxy between JavaScript and the DataBase, without having to post data to the server posting with such data also the whole page), this cannot be the place to explain what Ajax is, being alredy available so abundant a documentation out there about Ajax.
So, I shall presume you already have at least a general idea about what Ajax is.

There are also many Ajax classes on the internet; this one has the virtue of being very elegant in the following respects:
  • It's a class where all the codes are encapsulated within one single class - no prototype statements to add outside of it, no additional subroutines to help build the instance, and not even echo handlers as globally defined functions.
  • With the very same initialization line, you can also add as its argument to the constructor your own echo handling function, also as an anonymous one. Thus it's all very compact and smooth - why not saying it's elegant?
    var myajax=new Ajax();
    /*var keyword is necessary, class name has UPPERCase A*/

    //or, passing as parameter your echo handling function:
    var myajax=new Ajax( function(response){alert(response);} ); /*nice!*/

    //or you could also do:
    var myajax=new Ajax();
    myayax.echoFunction=function(response){alert(response);}
    /*echoFunction is a class property, and is case sensitive: it can host a function defined by you*/
  • You can define your own echo handler also by adding it to the class methods as an argument (if you prefer so) and/or override your own echo handlers any time by passing a echo handler parameter to the get and post methods when you call them (more about this later).
  • Using a surprising technique named currying I first heard of here, and getting deeper about it here (the most viable explanation about Lambda Calculus and currying I found after having checked many), the class can lend itself to initialize just whatever amount of instances in any page, all fully independent of each other and all working.
I am in the process of getting deeper with currying techniques and their meaning - basically it amounts to the following surprising syntax:
function add(x){return function(y){alert(x+y);}}

add(1)(2);//this WORKS and alerts... 3!
Hypothesis non fingo and whereas many would probably hurry to say to you it's crystal clear to them why that works, I with my humble 10 years of experience about Javascript won't declare such a falsity: the even most surprising fact with that, in fact, is that whatever you pass as argument into the first round brackets, will survive intact inside the innermost returned function.
This amazing characteristic, derived from what I learn being a Lambda Calculus implementation in Javascript, makes it possible to use any Ajax onreadystatechange event handler passing safely to it arguments and having full confidence they will survive asynchronous calls.

In fact an event handler in Ajax, when triggered, goes on being invoked in the background until the full response by the server hasn't been got: this means that when such function runs, any referenced instance called within it via the Javascript keyword this vanishes in thin air because the invocations in the background are asynchronous (=arrive randomly, not procedurally, suspending the echo function in the 'void' of possible laps and gaps, whereas the echo function loses contact with the instance that originally created it) and disentangle it from its direct relation with its specific class instance that originally triggered it (or, at any rate, from any direct relation accessible via the this keyword). This forced echo functions to be written as globally scoped functions (you will be surprised how many books sold for as little as 80$ each, all invariably 'suffer' of this very same issue and want of abstraction!), and/or to hardcode within them the name of the class instance they were dealing with. With this class this is not necessary, and the 100% level of generalization and abstraction I was after and struggling for is achieved.

Adopting a currying technique, I managed to avoid the above mentioned issue while at the same time using no prototype statement - which would have implied a somwehat 'undesirable' lack of containment, because such statement should have been included outside the class definition as additional lines of code unfit to be contained in one wrapper for all the code and all the instances.

Here follows the code of the class, then I shall explain briefly its methods. Before that, however, remember that Ajax connects javascript to a server scripting file (such as php or asp), and from it it grabs the first statement it echoes (prints).This means that you should handle in your server file all the incoming data arriving from Ajax as data that has to be sanitized with the same rigor you would with regular POST or GET data arriving via a regular form submission or URI (=web address).
Though it is not, as far as I know, widely documented, Ajax applications are vulnerable to be abused in order to perform DoS (Denial Of Service) Attacks. Instance:
javascript:while(1){ ajaxInstance.get('foo.php') }
To circumvent this, I may suggest to set within all your server side script meant to receive Ajax requests some code that checks whether the requests are arriving with a pace inferior or equal to say one millisecond (microtime) and that, when met such pace, logs out the user destroying the session or simply exiting (exit) the script.
topleftpixel.com

CLASS CODEX
Copy and paste
This is the codex:
topleftpixel.com

Its Methods
A quick review
There aren't many methods in it, and that's a virtue of the class: with such a flexible setting, not only you have already all that it takes to run Ajax (if you define no echo handler of your own, the default echo handler will store in a class property named response the server received response, which thus you can also handle at a second time if you prefer so!), but you can nest in it whatever else you want with great confidence.
We assume that the placeholder instance name of a validly initialized class instance is myajax
  • Method: myajax.initialize:
    consider it private: it just initializes the XMLHttp object. I had to give up trying to scan IE6 activeXObject like Msxml2.DOMDocument.5.0 because they were prone to trigger errors even within try/catch statements! So we default to Msxml2.XMLHTTP' for activeX - however we start with the option of having an XMLHttp object derived from a native XMLHttpRequest, which is what also Internet Explorer 7 will do.
  • Method: myajax.get:
    what said here applies also to the class method named post.
    These methods take in up to 4 arguments:
    1. String: the address of the server file to contact
    2. String: the appended query to the address above, without the ? mark.
      In fact Ajax can deliver to server side scripting engines parameters to make these parameters be used for server scripting manipulation. In a GET Ajax request, these will go in the very same fashion a GET request in an URI (=web address, URIs for dummies would say) would do. Namely they would be placed after the URI, putting first a question mark to specify the query portion of the URI starts and then what follows is the set of parameters in the traditional syntax:
      http://www.blahblah.com/?param1=value1&param2=value2&param3=value3
      etc.
      By the way, a side effect but good feature with Ajax is that, being arguably your URI included within the script, they will not infringe upon XHTML strict reliance -in case you really need it for purposes that are not mere vanity- namely they will not require the & being passed as &.

      Once again, remember: an Ajax request by all accounts is a submission of data to the server, although it may seem not so because it is working in the background: sanitize on the server side script all the data coming from Ajax with the same rigor and distrust (to borrow a term often used by Chris Shiflett, who often even suggested to be paranoic abut that - and rightly so, because you are bound to discover continuously that for how much you sanitize, eventually something ends up slipping in and carrying with itself the potential of running havoc), if not even with more than that distrust, you would use to sanitize all data passed to a server script by user generated inputs: in fact if forging a POST request requires XSS (Cross Site Scripting), forging an Ajax POST request may potentially require even less than that.
      Though it is not, as far as I know, widely documented, Ajax applications are vulnerable to be abused in order to perform DoS (Denial Of Service) Attacks. Instance:
      javascript:while(1){ ajaxInstance.get('foo.php') }
      To circumvent this, I may suggest to set within all your server side script meant to receive Ajax requests some code that checks whether the requests are arriving with a pace inferior or equal to say one millisecond (microtime) and that, when met such pace, logs out the user destroying the session or simply exiting (exit) the script.
    3. Function: an optional on the fly definition of an echo handler of your own, which may take in one argument that the class shall take care to pass to it: the server response!
    4. String: optional; the behaviour defaults to get as a response a string, if you want to grab XML data pass this as: 'responseXML'
    Do not be surprised if, in the codes of those methods, when I assign the echo handler for the state change event it seems that I am not assigning but actually running a function: it is actually a curried function so the first set of round brackets does not execute it, only a second set of round brackets would! I think that what happens with currying is that the first wrapping function creates a scope like an aura around the second (the encapsulated) function, and within such setting the arguments passed to the first function can bask and survive the rounds expleted by the encapsulated one because they still belong and loiter inside the encapsulator.
    Remember?
    function add(x){return function(y){alert(x+y);}}

    add(1)(2);//this WORKS and alerts... 3!

    alert(add());/*this alerts the encapsulated function... definition! so add() is a function itself*/
  • Method: myajax.head:
    same as for the methods get and post applies, but it accepts only the first 2 arguments described there.
  • Method: myajax.echo:
    this is where the handling occurs. If an echoHandler has been defined by you in the ways mentioned in the first 'chapter' above, then this method will call your defined echo handler once the ready state status is achieved, passing to it the response - and still keeping contact with its instance by currying techniques.
Of course, some code and a test may be benefical. Thus, below is the code that initializes two instances of the Ajax class to show they coexist, it initializes within their constructor a specific echo handler that will store the echoes in a window scoped variable, and we will issue two parallel Ajax calls to two different php files to see what they return.
To see the test in action, click first the button RUN and then the button RESULTS (wait a second -or less- before clicking RESULTS, after you have clicked RUN, so you will be sure the asynchronous calls are on readyState complete. In the worst case if you see no readable result alerted upon clicking RESULTS, wait two seconds):
var storingvar='';

var ajax1=new Ajax(
	function(response){storingvar+="\n\n"+response;}
);

var ajax2=new Ajax(
	function(response){storingvar+="\n\n"+response;}
);

ajax1.get('file1.php'); ajax2.get('file2.php');



Have fun. And keep the ending comment, as I keep the links here to the places I checked to get some conceptual help for the echo function vanishing reference to the this javascript keyword in developing this class.
topleftpixel.com