ajaxik, the tiny ajax
03 November 2006 // javascript. things.
Ajaxik is a tiny javascript library for basic ajax interaction, can also be used for "lazy" ajax (without javascript programming).
lazy ajax
At page load time, Ajaxik finds forms and links in document, that have jtarget attribute and makes them ajax'able. When user clicks such a link (or submits such a form), server response will be inserted in a html element instead of reloading the whole page. The value of jtarget should be an ID of that element.
<a href="/files/ajaxik/test.php" jtarget="BOX">click me</a>
<div id="BOX"></div>
If for some reason ajax cannot be started or any kind of error occurs during transfer, Ajaxik "downgrades gracefully" and just follows the link (or submits).
on-demand initialization
If you feel uncomfortable with a non-standard attribute and autoload, you can also ajaxize html elements in an unobtrusive way.
Ajaxik.enable(element, target)
This makes given element (link or form) ajax'able. element and target are DOM objects or their ids. No changes in html are needed.
<div id="LINKS"><a href="/files/ajaxik/test.php">click me</a></div>
<div id="BOX"></div>
....
<script>
window.onload = function() {
Ajaxik.enable(
document.getElementById("LINKS").firstChild,
"BOX")
}
</script>
loading feedback
When Ajaxik starts receiving data from the server, it searches for a special event handler on the target element: onajax . If defined, the handler is invoked with three arguments: readyState (which is XMLHttpRequest readyState property), text (= server response, responseText) and xmlhttp (XMLHttpRequest itself).
<a href="/files/ajaxik/test.php" jtarget="BOX_2">click me too</a>
<div id="BOX_2"
onajax="this.innerHTML = (readyState==4) ? text : 'Loading...' "
></div>
Note that if you define the handler directly in HTML (like above), you should name the arguments exactly as documented. Out-of-line definition allows arbitrary argument names:
someElement.onajax = function(ready, text_from_server, xml_http) { ... }
on the server side
Ajaxik adds __ajax__ variable (equal to some random integer) to the request. This makes it possible for server-side script to tell the difference between "normal" and ajax calls, e.g.
if(isset($_REQUEST['__ajax__']))
// output only updated block
else
// output whole page
api
For direct http communication there are two methods in Ajaxik, get and post :
Ajaxik.get(url, proc);
Ajaxik.post(url, data, proc);
proc is an (optional) onpropertychange callback, that takes three arguments: readyState, text and XMLHttpRequest object.
Ajaxik.get('page.php', function(readyState, text, xmlhttp) {
if(readyState == 4) {
if(xmlhttp.status == 200)
alert(text);
else
alert("Error!");
}
})
comment on this