AJAX – Getting Started ExtJs with Perl CGI

I usually use ExtJs with Struts, PHP, or Google Web Toolkit (GWT). Here i will create a simple tree panel sample using ExtJS and Perl CGI.

Here is our directory structure:
-extjs (directory)
-JSON (directory)
-data.cgi (file)
-index.html (file)
-JSON.pm (file)

1. Download the latest Ext Js from here and extract the archive files to extjs folder
2. You have mod Perl cgi enabled with your apache server, you can see my post at Perl for how to set up mod mod Perl CGI in apache
3. JSON module for Perl, you can download it from here

Enough talk, let’s start coding!

Filename: index.html

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
<link rel="stylesheet" type="text/css"
	href="extjs/resources/css/ext-all.css" />
<script type="text/javascript" src="extjs/adapter/ext/ext-base.js"></script>
<script type="text/javascript" src="extjs/ext-all-debug.js"></script>
<script type="text/javascript">
	Ext.onReady(function() {
		var Tree = Ext.tree;
		var tree = new Tree.TreePanel( {
			el : 'tree-div',
			autoScroll : true,
			border: false,
			title: 'My First Panel',
			animate : true,
			enableDD : true,
			containerScroll : true,
			loader : new Tree.TreeLoader( {
				<strong>dataUrl : 'data.cgi'</strong>
		// set the root node
			var root = new Tree.AsyncTreeNode( {
				text : 'Ext JS',
				draggable : false,
				id : 'source'

			 // render the tree

<div id="tree-div" style="overflow:auto; height:300px;width:250px;border:1px solid #c3daf9;"></div>

As you see above code, the treepanel gets the data url from data.cgi. What is this data.cgi produce? the data.cgi will response JSON type to the html, JSON is optimized version of XML.

2. data.cgi

#!/usr/bin/perl -w
use CGI;
use CGI::Carp qw(fatalsToBrowser);
use Storable;
use JSON;
$page = new CGI;

print "Content-type: application/json\n\n";


$text = objToJson(\@mydata);

print $text;
exit (0);

Open your browser and point to http://localhost/extjstest/index.html. If everything fine, you should see a treepanel displayed.