Prototype



Prototype is one of the original JavaScript libraries and is used widely. It makes AJAX calls very easy.

XMLHttpRequests with Prototype

Suppose that you have the following XML file about the Three Stooges.

<?xml version="1.0"?>
<stooges>
   <name>Larry</name>
   <name>Moe</name>
   <name>Curley</name>

</stooges>        
        

Here is the only code that you need (shown below in red) to make an XMLHttpRequest when you use the Prototype library. I supplied my own code (show below in blue) to unpack the XML content received.

<script src="prototype-1.6.0.2.js" type="text/javascript"></script>
	
<script type="text/javascript">
		
var myAJAX = new Ajax.Request('stooges.xml',
{	
method:'get',
onSuccess: function(transport){
  var response = transport.responseXML || "no response XML";
  showXML(response);
},
onFailure: function(){ alert('Something went wrong...') }
});

	
function showXML(response)
{
	var root = response.documentElement;
	var children = root.childNodes;
	for( var i = 0; i < children.length; i++)
	{
		if(children[i].nodeName == "name")
		{
			alert(children[i].firstChild.nodeValue);
		}
	}
}
		
</script>

Web page updates via HttpRequests

Prototype also has a nifty method "updater" that permits you to designate a web page element and then update it via a HttpRequest.

Note that my example uses simple text files so that I don't have to fool with server-side code at this point. In a "real" implementation, you might supplement the updater method call with some parameters. The server would respond to these parameters by initiating database calls, file IO, XML manipulation, etc., to produce some HTML content to return to the client web page. In this example, I use text files so that I can receive the contents of the HttpRequest and paste it directly into the web page.

Suppose that I have two text files called "one.txt" and "two.txt" with this content:

This is file one.
 
This is file two.

And suppose that I have an HTML element with an id attribute.


<p id="upDateMe" style="color: yellow; background:green">null</p>

Prototype Updater

null


Click me: File One


Click me: File Two

The magic that does the HttpRequest, targetting the webpage element id "upDateMe" and patches the content into the webpage is this:

function doOne()
{	
    var j = new Ajax.Updater('upDateMe', 'one.txt', { method: 'get' });
}
function doTwo()
{
    var k = new Ajax.Updater('upDateMe', 'two.txt', { method: 'get' });
}		

If the server responds with a heavier package - a JSON object or an XML object - then you would have to do some unpacking and pasting it into your webpage.