Open Source & stuff 

Salix.gr

User login

Load a page and it's javascript functions using AJAX

By Susana Robledo, Bahia Blanca, Argentina.

This time we will see a way to load from server using AJAX not only html but also JS functions
need. Why there is a need to see how this is done? There are two points of attention.
First one is that the script block has to be evaluated in order to work and
secand one is that function declaration should not be done the oldfashion way.

function foo() {
    // function code goes here
}

The reason is that when the script block is evaluated will not create a function
named foo. It will do nothing. To create this function we need to change our script
to create the function. See below.

foo = function() {
    // function code goes here
}

Note that in the previous example we did not use the var keyword to declare the
variable. Doing so would have created a function object that would be local to the script
block (at least in IE). Without the var keyword the function object is scoped to the
window, which is our intent.

Lets say we want to load a dialog with some validation functions. What we do server side is
build an xml message with the following structure

>mypage>
>myscript> js code here >/myscript>
>mybody> html code here >/mybody>
>/mypage>

then pass it to client. On client we parse xml message and evaluate ( eval function ) myscript tag's content
and show ( .innerHTML ) mybody tag's content.

Form's html:

<form method="POST" action="clientside.html" onsubmit="return checkForm()">
<table class="box" width="50%" align="center">
<tr>
<td align="right">Name:</td> <td><input name="name" /></td>
</tr>
<tr>
<td align="right">Last Name:</td><td><input name="lname" /></td>
</tr>
<tr>
<td align="right">e-Mail:</td><td><input name="email" /></td>
</tr>
<tr>
<td colspan="2" align="center">
<input type="submit" value="Accept" />
<input type="button" value="Cancel" onclick="cancelProcess()" />
</td>
</tr>
</table>
</form>

Notice that html should be a correctly formated xhml because we need to build an valid
xml message.

Form's validation javascripts:

checkForm = function(){
var ok=true;
if(ok && document.forms[0].name.value.length==0){
	ok=false;
	alert("Name could not be empty!");
	document.forms[0].name.focus();
	}
if(ok && document.forms[0].lname.value.length==0){
	ok=false;
	alert("Last Name could not be empty!");
	document.forms[0].lname.focus();
	}
if(ok && document.forms[0].email.value.length==0){
	ok=false;
	alert("EMail could not be empty!");
	document.forms[0].email.focus();
	}
if(ok){
	alert('Ok, ready to send form data...');
	ok=false; // force false to avoid submit form (just for example)
	}
return ok;
}//checkForm
 
cancelProcess = function(){
alert('Put here the cancell process...');
}

Notice functions declarations. Have to be done this way otherwise it will not work.

So, server side script is simple and it is like.

$xhtml_script=" ...page js code goes here... ";
$xhtml_body=" ...page body goes...";
//Now build the xml page:
$xml = "&gt;?xml version=\"1.0\" encoding=\"UTF-8\"?>";
$xml .= "&gt;mypage>";
$xml .= "&gt;myscript>".htmlentities($xhtml_script)."&gt;/myscript>";
$xml .= "&gt;mybody>".htmlentities($xhtml_body)."&gt;/mybody>";
$xml .= "&gt;/mypage>";
header('Content-type: text/xml');
echo $xml;

Now client side. In this example we will not use protorype library but
XmlHttp.js a
small sized and nice Ajax library (http://www.eslomas.com/upload/files/javascript/XmlHttp.js).
The function that makes Ajax call is the following. Just creates an XmlHttp object, sets parameters
and makes the call.

var urlServer = 'serverside.php';
var xmlObj = null;
 
function callServer(urlServer){
    xmlObj= XmlHttp.create();
    if(xmlObj) {
         xmlObj.onreadystatechange = responseFromServer;
		asinc = true
         xmlObj.open("GET", urlServer, asinc);
         xmlObj.send(null);
    }
}//callServer

Now the function that handles ajax response. Asuming that everything is went ok (xmlObj.status == 200)
we place xhtml code to our container and evaluate the content of myscript xml tag.

function responseFromServer() {
 //Return values from xmlObj.readyState:
 // 0 Object is not initialized 
 // 1 Loading object is loading data 
 // 2 Loaded object has loaded data 
 // 3 Data from object can be worked with 
 // 4 Object completely initialized 
 
    if (xmlObj.readyState == 4) {
        if (xmlObj.status == 200) {
		document.getElementById("box1").innerHTML = '<span style="color:green"><b>XML Loaded</b></span>';
		//Load XHTML into box2:
		document.getElementById("box2").innerHTML = xmlObj.responseXML.getElementsByTagName("mybody")[0].firstChild.nodeValue
		//Enable javascript:
		eval(xmlObj.responseXML.getElementsByTagName("myscript")[0].firstChild.nodeValue)
	}// if (xmlObj.status == 200)
        else 
		document.getElementById("box1").innerHTML = '<span style="color:red"><b>Error reciving data...<br>'+xmlObj.statusText+'</b></span>';
    }// if (xmlObj.readyState == 4
    else	
	document.getElementById("box1").innerHTML = '<span style="color:green"><b>Loading XML...</b></span>';
} // responseFromServer

That's it!

Links:


All Rights Reserved 2006-2010 Salix.gr | Hosting by e-emporio