Friday, June 12, 2009

AJAX - with no framework

My initial implementation of ajax involved three files.
1 - a form - that called the javascript
2 - javascript file, that contained funtion called by the form and called the model component - that goes to the db.
3 - a model component (CFC, class etc) that speaks to and retrieves the data and sends back

No framework, or complex JSON stuff. The javascript is really the heavy hitter here, since it is invokes, does the invoking, and tells the html div element to update with the content from the db.

Here is some sample code that does this.

1 - form that calls the jscript function


<form>
<div>
<span>
<b>Select a pi key group:</b>
</span>
<span>
<select name="Country" onChange="getPIs(this.value)">

<option value="h">like h</option>
<option value="r">like r</option>
<option value="p">like p</option>
</select>
</span>
</div>
<div id="piList">
</div>
</form>


2 - the javascript function getPIs is called in step 1 in the onchange event for the selector. In the getPIs function below - a url variable is set that points to my cfc that contains the function that goes to the db. Then a GetHttpObject call is made and assigned to the xmlhttp variable. In the stateChanged function that is passed as an argument to the GetHttpObject function, there is a reference to a div layer that is in the view page that is calling the jscript. That is the connection or the place where the result of the cfc call will output.


function getPIs(str)
{
var url="model/ajaxCalls.cfc?Method=getPIKeys&pikey="+ str;
xmlhttp=GetHttpObject(stateChanged)
xmlhttp.open("GET", url , true)
xmlhttp.send(null)
}

function stateChanged(){
if (xmlhttp.readyState==4 || xmlhttp.readyState=="complete"){
document.getElementById("piList").innerHTML=xmlhttp.responseText
}
}

function GetHttpObject(handler){
try{
var oRequester = new XMLHttpRequest();
oRequester.onload=handler
oRequester.onerror=handler
return oRequester
}
catch (error){
try{
var oRequester = new ActiveXObject("Microsoft.XMLHTTP");
oRequester.onreadystatechange=handler
return oRequester
}
catch (error){
return false;
}
}
}

3 - here is the coldfusion cfc method invoked by the jscript call

<cffunction name="getPIKeys" access="remote" returntype="any">
<cfargument name="arg1" type="any" required="No" default="h">

<cfquery name="q" datasource="accelerateu">
SELECT strandID, piID, auID, piKey, piDescription, piCode
FROM dbo_performanceIndicator

WHERE (piKey LIKE '%#arguments.arg1#%')
</cfquery>

<cfsavecontent variable="bob">
<cfoutput query="q">
<b>#pikey#</b> - #piDescription#.
<br/>
</cfoutput>
</cfsavecontent>

<cfreturn bob>
</cffunction>


This example is not real pretty and only executes in FF, not IE. This example does demonstrate a simple AJAX solution. It was for me, a natural first step. That being said, let me share some of my next step learning experiences in the next post.

No comments:

Post a Comment