Building a bridge between server and client side using Ajax
Ok, so we now have a PHP script that gets the contents of a remote RSS (XML) file and returns it back to the browser as is. Yes, technologically it's a wonder, but to the viewer, it's not easy to appreciate. The RSS file remains its initial bland and baffling appearance. This is where Ajax comes in, by building a bridge between the returned RSS content and JavaScript with its ability to return the contents of any file either as raw text or a XML object (if applicable) to JavaScript for further processing. Lets see a simple example now of how to use Ajax to retrieve the contents of a XML file and return it to JavaScript as a XML object:
<script type="text/javascript">
function createAjaxObj(){
var httprequest=false
if (window.XMLHttpRequest){ // if Mozilla, Safari etc
httprequest=new XMLHttpRequest()
if (httprequest.overrideMimeType)
httprequest.overrideMimeType('text/xml')
}
else if (window.ActiveXObject){ // if IE
try {
httprequest=new ActiveXObject("Msxml2.XMLHTTP");
}
catch (e){
try{
httprequest=new ActiveXObject("Microsoft.XMLHTTP");
}
catch (e){}
}
}
return httprequest
}
function ajaxshowme(){
ajaxinstance=createAjaxObj()
xmlindicator=(arguments.length>0)? 1 : 0
var parameters="id=CNN&cachetime=5"
ajaxinstance.onreadystatechange=alertcontents
ajaxinstance.open('GET', "rssfetch.php?"+parameters, true)
ajaxinstance.send(null)
}
function alertcontents(){
if (ajaxinstance.readyState == 4){ //if request of file completed
if (ajaxinstance.status==200){ //if request was successful
if (xmlindicator)
alert(ajaxinstance.responseXML)
else
alert(ajaxinstance.responseText)
}
}
}
</script>
<a href="javascript:ajaxshowme()">Contents of CNN RSS feed</a>
Example: Contents of CNN RSS feed (text)
This is just a skeleton Ajax script that makes a GET request asynchronously, in this case, to "rssfetch.php?id=CNN&cachetime=5" The "responseText" property returns the output of the request, or the raw contents of the requested RSS feed. But wait, that's not actually what I want! PHP already took care of the raw part, the goal of Ajax is to create some meaning out of it. With that said, the Ajax property I'm really interested in is "responseXML", which returns the requested XML document as a JavaScript XML object that can then be easily parsed using JavaScript. Here's a demo of the above example again, but this time, with the "responseXML" property used instead:
Example: Contents of CNN RSS feed (xml object)
We've captured the genie in a bottle by invoking "responseXML"- now the XML document is much more palatable to any JavaScript that attempts to make sense out of its contents. The time is ripe to create a RSS JavaScript ticker.
- RSS Ajax JavaScript Ticker
- A PHP script to get the contents of a remote file
- Building a bridge between server and client side using Ajax
- An RSS + Ajax + JavaScript ticker