Categories

AJAX example

There are tons of places on the net where you can find some ajax tutorial on how to make hidden calls to the server.
Anyway, I put here a basic javascript function (may be more for my reference). For instance I have to send three parameters v1,v2,v3 to the checkdate.php server page and receive back a code. If the code is equal to 1, then I show the errors’ layer and hide the buttons’ layer.

function ajaxsend (v1,v2,v3)
{
var xajax = null;

if(window.XMLHttpRequest) xajax = new XMLHttpRequest();
else if(window.ActiveXObject) xajax = new ActiveXObject “Microsoft.XMLHTTP”);
else return(false);

var str = “chky=”+v1+”&chkm=”+v2+”&chkd=”+v3;
xajax.open(”POST”,”./checkdate.php”,false);
xajax.setRequestHeader(”Content-Type”,”application/x-www-form-urlencoded”);
xajax.send(str);

if(xajax.readyState == 4) {
if (xajax.responseText==”1″) { //<15years
hide(’buttons’);
show(’errors’);
}
}
}

Just to be complete, here are the two functions hide and show, written in a “browser independent” way:

function show(layer_ref) {

if (document.all) { //IS IE 4 or 5 (or 6 beta)
eval( “document.all.” + layer_ref + “.style.display = ‘block’”);
}
if (document.layers) { //IS NETSCAPE 4 or below
document.layers[layer_ref].display = ‘block’;
}
if (document.getElementById &&!document.all) {
mylayer = document.getElementById(layer_ref);
mylayer.style.display = ‘block’;
}
}

function hide(layer_ref) {

if (document.all) { //IS IE 4 or 5 (or 6 beta)
eval( “document.all.” + layer_ref + “.style.display = ‘none’”);
}
if (document.layers) { //IS NETSCAPE 4 or below
document.layers[layer_ref].display = ‘none’;
}
if (document.getElementById &&!document.all) {
mylayer = document.getElementById(layer_ref);
mylayer.style.display = ‘none’;
}
}

I hope you will find this example useful!

Comments are closed.

Cyberactiva web development - Blogged