Jul
The standards and requirements of web-based user interfaces have steadily risen in recent years, and heavy use of Javascript and sometimes AJAX is almost unavoidable in modern day web applications. However, developing with Javascript could be similar to pulling teeth - There’s a lot of bleeding and the pain won’t go away for several days (Incidentally, I had a tooth pulled out recently).
Javascript, unlike server-side languages such as PHP, are parsed by the browser, and is browser-dependent in its functionality and debugging process. As fate would have it, all browsers differ from each other in their implementations of Javascript parsing, often times even diverging on different versions of the same browser. And of course, there is also Internet Explorer, whose vile and unspeakable acts of Javascript terror are only surpassed by its level of adherence to Css standards.
For basic usage, plain old Javascript can still make do and create simple user-interface interactions. But when the user-interface requirements are high, and Javascript deployment is massive, other alternatives might be considered.
Developing with Javascript Frameworks
The first logical step would be picking up a good Javascript framework. Javascript frameworks aim to provide expansive common functionality in simpler format (usually using Object Oriented design methods), are supposed to be relatively bug free since they are public domain and are usually actively supported by their communities.
There are several very good Javascript libraries/frameworks, including but not withstanding:
jQuery, Prototype, Dojo, YUI,mootools, all of which provide methods to traverse and manipulate the DOM (the inner workings of an HTML page), remote scripting such as AJAX and several other variations, animations and event handling (events are user interface interactions such as clicking on button or submitting a form).
I personally use jQuery since I like its small footprint (20Kb!) and design concept (fluent interface, reduces your amount of code), but the others are all very good and a short google search could bring you many comparisons between those frameworks.
Some notes:
jQuery was recently released in version 1.1.3.1 which offers many speed enhancements over 1.1.2 and a long list of bug fixes. If you haven’t tried it yet, now’s the time.
Dojo is currently in beta stage of their 0.9 version and shows a lot of promise to one day becoming the most prominent JavaScript library/toolkit available. Their development team’s vision and ambition is quite impressive.
Javascript And Common Sense Are Like Apples And Oranges
So once I pick up a good Javascript framework, I now start writing my own Javascript code using the provided functionality and things start to go haywire a small bit. JAVASCRIPT DEBUGGING IS HARD, I think to myself, seeing obscure error messages flying around (why is an object expected on line 1792? I could swear I had only 200 lines of code… Could it be the framework I choose aggregates my error messages? :gasp:) which appear randomly at different browsers (Why isn’t it working in IE? It was just working in firefox… Why is IE evil? Is it by design or some part of a grand scheme to provide the ultimate browsing experience sometime in 2043?).
There are several useful tools for debugging Javascript, the most useful by far being FireBug, but alas, its only for FireFox. A Javascript implementation of it exists (I could make a sarcastic remark on this but I refrain) for IE, which emulates some basic debugging functionality. There’s a long list of tools for debugging Javascript over at the DOJO Toolkit, a very useful article all around.
After this lengthy introduction, I’ll get to main issue -Increasing productivity and reusability using Javascript by abstracting its use through a server side language. I will discuss PHP implementation since it is my server side scripting language of choice for web development.
Abstraction is not a buzzword
When I say abstracting Javascript use, I mean creating PHP OO classes that contain logic for Javascript use. Server side scripts are much easier to debug, and are not browser dependent. So hopefully, when I manage to create a working Javascript solution to some common problem, I will contain it’s usage in a PHP class so there will no more syntax errors that are so hard to track down in Javascript. I would like also to decouple dependencies on a specific Javascript framework, in case I want to switch or mix and match. Last but not least, I would like to control user-interface events (onclick, onmouseover and so forth) from the PHP code, without polluting the html output with the actual event attributes (no more onclick=”dostuff();”) by using event handlers and listeners.
The Approach
I start by creating a class that represents Html elements. I want this class to achieve two major objectives:
1. To allow me to pass a Javascript class an object whose properties it is familiar with, and has methods for easy manipulation of those properties.
2. Creating valid Html elements that will mainly conform to w3c specification, but more importantly, will never break my Html page presentation.
3. Using this class to abstract common cross-browser HTML and CSS issues, which will save tremendous time and will clean up the view interface removing many php if..else clauses.
A general structure of such a class would look like this (I use the name Xhtml since I would like to create Xhtml valid elements):
Xhtml Class
/**
* XHTML Tag methods and properties class
*
* @package HTML
* @author Eran Galperin
* @copyright Lionite 2007 *
* @version 0.5 alpha
*/
abstract class Xhtml
{
/**
* Tag name, must be defined in child class
* @var string Tag name
*/
protected $_tag = null;
/**
* Attributes storage array
* @var array Attributes array of attribute name => value
*/
protected $_attrib = array();
/**
* Contained HTML string
* @var string Element HTML contents, between
* starting tag and closing tag, where relevant
*/
protected $_html = null;
/**
/* Is object an empty tag
/* An empty tag is a tag that has only a starting tag, for example the 'img' tag.
/* @var boolean $_isEmpty
/**
protected $_isEmpty = false;
}
Three basic members, one indicating the tag name (’div’,’span’,'a’ and so forth), one containing all the properties of the element, and one containing the Html contents of the element, where relevant (not relevant for single tag elements).
Next I will add some basic methods for manipulating and rendering the Html element:
...
/**
* Set XHTML element HTML contents
*
* Sets the HTML contained between an opening and closing tag for an HTML
* element. Returns contained value is passed a null parameter, or object
* otherwise for fluent interface
* @param string $html Element contents
* @return object, $this
*/
public function html($html = null)
{
if(is_null($html)){
return $this -> _html;
}
$this -> _html = (string)$html;
return $this;
}
/**
* Set class attribute
*
* Since 'class' is a protected word in PHP this method implements an alternative. Also allows
* for aggregation of Xhtml object classes by default.
* @param string $class Name
* @return object, $this
*/
public function setClass($class = null,$aggregate = true)
{
if(is_string($class)){
if(isset($this -> _attrib['class']) && $aggregate === true){
$this -> _attrib['class'] .= ' ' . $class;
} else {
$this -> _attrib['class'] = $class;
}
}
return $this;
}
/**
* Set XHTML tag attributes
*
* Sets an array of attributes using 'attribute name' => 'attribute value' scheme
* Alternatively, a pair of attribute name and value can be passed as strings.
* If an array is passed in the $value argument, it is used to filter the attributes array.
* An empty call will return the currently set attribute array, and a call with just an attribute name
* as the first argument will return that attribute current value if set.
*
* @param mixed $attrib Attribute array definition or key value
* @param mixed $value Value paramter of attribute
* @return object, $this / array Attributes
*/
protected function attrib($attrib = null,$value = null)
{
if(is_string($attrib) && is_string($value)){
$this -> _attrib[$attrib] = $value;
} else if(is_string($attrib) && isset($this -> _attrib[$attrib])){
return $this -> _attrib[$attrib];
} else if(is_array($value) && is_array($attrib)){
foreach($value as $filterKey){
if(isset($attrib[$filterKey])){
unset($attrib[$filterKey]);
}
}
$this-> _attrib = $attrib;
} else if(is_array($attrib)){
$this -> _attrib = $attrib;
} else if(is_null($attrib)){
return $this -> _attrib;
}
return $this;
}
/**
* Trap unknown function calls and parse them to attributes declarations
*
* @param string $name Called method name -> parses to attribute name
* @param array $args Array of passed arguments
* @return object, $this
*/
public function __call($name,$args)
{
if(is_string($args[0])){
$this-> attrib($name,$args[0]);
}
return $this;
}
/**
* Conversion of attributes array to key="value" HTML properties syntax.
*
* @param array $attrib HTML attribArray key => value pairs
* @return Formatted attribute string
*/
public static function attribution($attrib = null)
{
if(is_array($attrib)) {
$html = '';
foreach ($attrib as $key => $val)
{
$html .= ' ' . htmlspecialchars($key, ENT_QUOTES, 'UTF-8')
. '="' . htmlspecialchars($val, ENT_COMPAT, 'UTF-8') . '"';
}
return $html;
}
}
/**
* Finalize HTML Tag Properties
*
* @return string HTML attributes declaration
*/
protected function finalize()
{
if(isset($this -> _attrib) && is_array($this -> _attrib) &&
!empty($this -> _attrib)){
return self::attribution($this -> _attrib);
}
}
/**
/* Perform Xhtml to String conversion
/* Attempts to return Xhtml valid code from the object structure
/**
public function render()
{
if(!is_string($this -> _tag)){
throw new Exception('$_tag property is not properly defined, should be a string');
}
$html = '<' . $this -> _tag . $this -> finalize();
if($this -> _emptyTag){
$html .= ” />\n”;
} else {
$html .= ‘>’ . $this -> _html . ‘<' . $this -> _tag . “>\n”;
}
return $html;
/**
* Trap Object to string conversion
* Attempts to run class method render()
*/
public function __toString()
{
return $this -> render();
}
And so we have a basic template for extending into concrete Html classes. You might have noticed I like to return the operating object via return $this so I can chain method calls. Also, a lazy attribute setting is activated using the __call() magical method to trap unknown method calls. Since class is a reserved word in PHP I had to add a setClass method for setting the class attribute.
Usage would look something like this:
<?php
$htmlObj = new Xhtml();
$htmlObj -> id('someclass') -> setClass('someclass') -> html('greatcontent');
echo $htmlObj;
?>
This usage will of course fail since Xhtml is an abstract class.
But ignoring that, upon echoing it will call the magical __toString() method which will try to create a string output using the render() method. Classes extending Xhtml should specify class member $_tag and optionally $_isEmpty to make rendering accurate.
Lets take a look at a real implementation of this abstract class, the code is very simple:
/**
* HTML Div tag class
*
* @see Xhtml
* @author Eran Galperin
* @copyright Lionite 2007*
* @package HTML
* @version 0.5 alpha
*/
class Div extends Xhtml
{
/**
/* Class tag name definition
/**
protected $_tag = 'div';
}
Side Note: In my full class hierarchy, the Xhtml class extends a class called Css which is dedicated to handling Css styling. I use it to abstract solutions to many common cross browser issues, such as handling transparent .png images, opacity and so forth, and to also provide Xhtml object with several utility methods for styling in a fluent short-hand interface. I might write a post on it in the near future. For consistency, I removed all reference of the Css class from the Xhtml class code.
So with this template we can create all the basic html elements. The more complex ones (such as table) require somewhat different implementation, and can also store more logic (such as handling alternating row styles and so forth).
I will move on to the actual JavaScript abstraction class that relies heavily upon the Xhtml in my next post (which I hope will come soon, since I’m swamped with work. Your feedback could help me clear some time for it ;] ).
@Disclaimer: Feel free to use the provided code, but please attach a reference and the copyright notice.





Thanks for this article,
I am looking for a solution to write Ajax code that can be switched off if Javascript is not enabled on the client.
Therefore, onclick, onmouser and so on should integrate the button only when Javascript is enabled, otherwise, the button would be a normal submit.
I believe the solution lies in handling the form with either hidden fields and submit button when javascript is disabled. Otherwise, no form, no hidden fields are populated. Instead, the query string to process through ajax is built using the same variables.
I am more than eager to have your feedback on this
Comment by Herve — 26 Apr @ 2:55 pm
In my opinion use a form for both cases (javascript on or off), with hidden inputs for the rest of the variables.
Attach a submit event to the form via javascript (if you are using jQuery, read this), and inside the event callback prevent the regular submit event from happening using the preventDefault() method. ie:
$('form#myform').submit(function(event){
//Prevent the regular submit event
event.preventDefault();
//Serialize all the form variables
var params = $(form).serialize();
.... do stuff with variables, like sending them via ajax ...
});
If javascript is disabled on the client, the event will not be attached, and the form will be submitted like a regular form. Hope this helps
Comment by Eran Galperin — 26 Apr @ 9:15 pm