In previous posts, I explained the process of requesting a URL for Ajax:
First, create the XMLHttpRequest object
Second, open a connection to a URL
Third, send the request
Finally, listen for a response from the server
Between the third and last step, however, there is a crucial piece: Creating data on the server that will be used by Ajax. This is actually quite simple. All that’s needed is an XML document, which can be creating in many different ways. The example I provide below is created with ColdFusion.
<cfsetting showdebugoutput = ‘false’>
<cfheader name=”Expires” value=”#now()#”>
<cfheader name=”Content-Type” value=”text/xml”>
<cfquery datasource=”mydatasource” name=”qryColors”>
SELECT Colors
FROM Products
</cfquery>
<cfoutput>
<colors>
<cfloop query=”qryColors”>
<color>#qryColors.Color#</color>
</cfloop>
</colors>
</cfoutput>
In the previous example, the first three lines simply specify that this is going to be an XML document. Then a query is run and looped over while creating XML nodes. This is the XML that will be sent back to the Ajax application. Once the response has been received in JavaScript, this XML can be used. Inside the listener response (when the readyState is 4), get the XML nodes of interest as follows (this is JavaScript code now):
colors = objXHR.responseXML.getElementsByTagName('color');
for (i=0;i<colors.length;i++)
document.write(colors[i].firstChild.nodeValue);