Working With AJAX and Perl with example

Hello,

While doing Ajax Perl application development, I came across an interesting article on the following link.

The article demonstrate with an example how Ajax can be used with Perl.  In the example given, there is table containing Student names and Marks. Every row has an Edit button, by which user can edit the information for that row. THE DB used is Microsoft Access to keep things simple. In order to run the below example code you will have to create a table by the name “Student” in MS Access”. It should have the following columns.

Column Name Data type Sl_No(Primary Key) Number Name Text Marks Number

Also you need to create a DSN by the name “mydsn” pointing to the Access DB.

The basic logic here used in the example is that we have two separate rows for View and Edit (for every Student). Initially we hide the Edit row (by using style=”display:none”) and display the View Row(by using style=”display:block”). When the user clicks on the “Edit” button, the View row becomes hidden and the Edit row is displayed. We have used JavaScript to toggle between the rows. Below is the code snippet used in files (AjaxExample.pl and student.js).

============================================================

AjaxExample.pl

============================================================

#!perl

use DBI qw(:sql_types);

use CGI;

use CGI qw/:standard/;

use CGI::Ajax;

my $cgi = new CGI();

#——————————————————————–

# Mapping the Perl subroutine to the triggering function

#——————————————————————–

my $ajax = new CGI::Ajax( ‘saveStudInfo_JScript’ => &saveStudInfo_PerlScript );

$cgi->header(-charset=>’US-ASCII’);

print $ajax->build_html($cgi,&generateHTML);

#——————————————————————–

# Subroutine which generates the HTML

#——————————————————————–

sub generateHTML {

# Hash which contains existing data

%Students = get_Student_Info();

$cnt = 1;

# Write the html code in the form of a string

$returnHTML .=  “n<HTML>”;

$returnHTML .=  “n<HEAD>”;

$returnHTML .=  “n<TITLE>Student Information</TITLE>”;

$returnHTML .=  “<SCRIPT language=”javascript” src=”/javascript/student.js” type=”text/javascript”></SCRIPT>”;

$returnHTML .=  “n</HEAD>”;

$returnHTML .=  “n<BODY bgColor=”#ffffff”>”;

$returnHTML .=  “<FORM  method=”POST” enctype=”multipart/form-data” name=”StudentForm”>”;

$returnHTML .= “n<BR>”;

$returnHTML .= “n<BR>”;

$returnHTML .= “n<TABLE cellspacing=”0″ cellpadding=”0″ align=”center”>”;

$returnHTML .= “n<TR><TD>”;

$returnHTML .= “n<TABLE width=”100%” align=”center” border=”1″ cellpadding=”3″ cellspacing=”1″ id= “StudentInfoTable”>”;

$returnHTML .= “n<TR>”;

$returnHTML .= “n<TD align=”center” >SL No</TD>”;

$returnHTML .= “n<TD align=”center”  nowrap>Name  </TD>”;

$returnHTML .= “n<TD align=”center” nowrap>Marks  </TD>”;

$returnHTML .= “n<TD align=”center” >&nbsp;</TD>”;

$returnHTML .= “n</TR >”;

foreach $key (sort { $a <=> $b }(keys %Students)) {

#View row

$returnHTML .=  “n<INPUT type=”hidden” name=”SerialNo” id=”SerialNo_$key” value=”$key”>”;

$returnHTML .= “n<TR style=”display:block”>”;

$returnHTML .=”n<TD align=”center” >$key</TD>”;

$returnHTML .=”n<TD align=”center”  nowrap><Div id=”Div_Name_$key”>”. (($Students{$key}->{Name}) ? $Students{$key}->{Name} : “&nbsp;”).”</DIV></TD>”;

$returnHTML .=”n<TD align=”center”  nowrap><Div id=”Div_Marks_$key”>”. (($Students{$key}->{Name}) ? $Students{$key}->{Marks} : “&nbsp;”).”</DIV></TD>”;

$returnHTML .= “n<TD  align=”center”><INPUT type=”button” name=”EditButton” value=”Edit” style=”cursor: hand; width: 40px” onClick=”makeRowEditable($cnt,’StudentInfoTable’)”></TD>”;

$returnHTML .= “n</TR >”;

#Edit row

$returnHTML .= “n<TR style=”display:none”>”;

$returnHTML .=”n<TD align=”center”  nowrap>$key</TD>”;

$returnHTML .=”n<TD align=”center”  nowrap><INPUT type=”text” size=”30″ id=”Student_Name_$key” value=”$Students{$key}->{Name}”  style=”text-align: center”></TD>”;

$returnHTML .=”n<TD align=”center”  nowrap><INPUT type=”text” size=”10″ id=”Student_Marks_$key” value=”$Students{$key}->{Marks}”  style=”text-align: center”></TD>”;

$returnHTML .= “n<TD  align=”center”><INPUT type=”button” name=”SaveButton” value=”Save” style=”cursor: hand; width: 40px” onClick=”saveStudInfo_JScript([‘Student_Name_$key’,’Student_Marks_$key’,’SerialNo_$key’,’NO_CACHE’],[‘Div_Name_$key’,’Div_Marks_$key’],’POST’);makeRowViewable($cnt,’StudentInfoTable’)”></TD>”;

$returnHTML .= “n</TR >”;

$cnt += 2;

}

$returnHTML .= “n</TABLE>”;

$returnHTML .= “n</TD></TR>”;

$returnHTML .= “n</Table>”;

}

#——————————————————————–

# Perl Subroutine which is called aschronously

#——————————————————————–

sub saveStudInfo_PerlScript {

# Accept Input

my $Name = shift;

my $Marks = shift;

my $SerialNo = shift;

# Call subroutine which does database update

update_Student_Info($SerialNo,$Name,$Marks);

# Return Output

return (@Return, ($Name ne “”) ? $Name : “&nbsp;”,($Marks ne “”) ? $Marks : “&nbsp;”);

}

#——————————————————————–

# Subroutine which fetches the data

#——————————————————————–

sub get_Student_Info {

my %Details;

my ($sql, $sth, $row);

# DSN with the name “mydsn”  points to the Db

$DB = “mydsn”;

# User name and password if any need to be specified. Currently no user name and pwd set.”;

$DB_USER = “”;

$DB_PASS= “”;

$dbh = DBI->connect(“dbi:ODBC:$DB”, $DB_USER, $DB_PASS);

$sql = “SELECT * FROM Student”;

$sth = $dbh->prepare($sql);

$sth->execute;

$cnt = 1;

while ($row = $sth->fetchrow_hashref) {

$Details{$cnt++} = $row;

}

$sth->finish();

return %Details;

}

#——————————————————————–

# Subroutine which updates the Student Table in DB

#——————————————————————–

sub update_Student_Info   {

my $SerialNo = shift;

my $Name = shift;

my $Marks = shift;

my ($sql, $sth,$row);

# DSN with the name “mydsn”  points to the Db

$DB = “mydsn”;

# User name and password if any need to be specified. Currently no user name and pwd set.

$DB_USER = “”;

$DB_PASS= “”;

$dbh = DBI->connect(“dbi:ODBC:$DB”, $DB_USER, $DB_PASS);

$sql  = “Update Student set Name = ‘$Name’,Marks = $Marks where Sl_No = $SerialNo “;

$sth = $dbh->prepare($sql);

$sth->execute;

$sth->finish();

return $sql;

}

============================================================

student.js

============================================================

/*

* Toggles the rows from EDIT mode to VIEW mode.

* Invoked on clicking the ‘SAVE’ button in last column.

*/

function makeRowViewable(rowNumber,id) {

var table = document.all ? document.all[id]  : document.getElementById ? document.getElementById(id) : null;

var editableRowNumber = rowNumber + 1 ;

var nonEditableRowNumber = editableRowNumber -1 ;

table.rows[editableRowNumber].style.display = “none” ;

table.rows[nonEditableRowNumber].style.display = “block” ;

}

/*

* Toggles the rows from view mode to edit mode.

* Invoked on clicking the ‘EDIT’ button in last column.

*/

function makeRowEditable(rowNumber,id) {

var table = document.all ? document.all[id]  : document.getElementById ? document.getElementById(id) : null;

var editableRowNumber = rowNumber + 1 ;

var nonEditableRowNumber = editableRowNumber -1 ;

table.rows[editableRowNumber].style.display = “block” ;

table.rows[nonEditableRowNumber].style.display = “none” ;

}


As we know, the term Ajax stands for ‘Asynchronous JavaScript And XML’. It is not a technology but a set of technologies being used together in a particular way. With effective use of existing technologies like HTML, DHTML, DOM, CSS, JavaScript one can make web pages more dynamic and interactive.

Using JavaScript, Ajax makes an asynchronous call to the server and fetches an XML document from a server-side component. Upon completion of the request, JavaScript may be used to update or modify the Document Object Model (DOM) of the HTML page. Only the necessary portions of the HTML DOM are re-rendered in the HTML page. In short Ajax techniques let you update parts of your web page without reloading the whole page.

The general benefit here is that an asynchronous operation executes in a separate thread. So when an operation is triggered asynchronously by the application, it can continue executing while the asynchronous method performs its task. Moreover only the data that needs to be updated or inserted can be sent instead of sending the entire form data. Perl Ajax framework are also available for faster development and test.

Popular web applications like  Gmail, Amazon, Orkut etc are using Ajax.

References and more links:

Simple Example demonstrating Ajax Implementation using Perl « Perl recipes « ActiveState Code.

http://www.perl.com/pub/2006/03/02/ajax_and_perl.html

http://perl.about.com/b/2006/03/17/using-ajax-from-perl.htm

http://ajaxpatterns.org/Perl_Ajax_Frameworks

http://search.cpan.org/~bpederse/CGI-Ajax-0.707/


Enjoy using Ajax from Perl.


Modern Perl Development and Perl 6

Hi

While watching a Perl 6 video on YAPC::EU 2010, I was wondering if year 2010 is going to be big for development in Perl programming or more specifically in Modern Perl based development (Moose,Catalyst etc). There are many new exciting module on Moose/MooseX, DBIx::class, Catalyst etc are uploaded on CPAN every month. I think the biggest news is the release of long awaited Rakudo Star in July 2010. This is a stable, usable Perl 6 implementation on Parrot Virtual Machine. Congratulations to all developers/testers of this project. One can download the tar ball the release from Github. I am going to explore and develop some applications using this exciting new language Perl 6.

I will try to show some exciting features of Perl 6 in my next post.

Happy programming!

Installing Perl modules with cpanminus

While browsing CPAN I found an intersting module by Tatsuhiko Miyagawa cpanminus.  Basically, this is a script to get, unpack, build and install modules from CPAN. The best part of  is it’s dependency free, requires zero configuration, and stands alone. When running, it requires only 10MB of RAM. [Source: CPAN]

There are Debian packages, RPMs, FreeBSD ports, and packages for other operation systems available. If you want to use the package management system, search for cpanminus and use the appropriate command to install.

You can also build from latest source itself.

I have tried it on my CentOs 4.6 and Windows XP machine. Some of the advantages which I can see at first place are:

  • It seems to consume lesser memory than traditional like CPAN and CPANPLUS which sometime goes out of the memory for heavy installation.
  • It’s provides really quiet installation in comparison to CPAN. Not many questions.
  • I think it’s good for beginners
  • Automates installation and install dependencies without CPAN installed so no need to download TAR unpack, makefile, make, make test stuff.

Will try to get some  more findings.

Cheers,

Installing Microsoft TrueType fonts (TTF) on CentOS 4.6 and RHEL 4

Default Linux installation (Cent OS in this case) doesn’t contain true type fonts. The application like open office, PDF generators requires proper fonts to embed into if not it will use the free system fonts which can create a lot of issues like  pdf, not showing content properly etc. It’s always good idea to install ms core fonts Well you can buy more fonts as per your requirement if you want.
To install the ms core fonts follow the below steps (Login as a ROOT):
Install RPM: Change the directory to download folder and run the follwing command:
#rpm -ivh cabextract-0.6-1.i386.rpm

Create RPM: Change the directory to download folder and run the follwing command
#rpmbuild -bb msttcorefonts-1.3-4.spec

(This step will download Microsoft CAB files and extracts the fonts and builds an RPM.  This will use system utilities [wget, rpm-build, chkfontpath, fc-cache, ttmkfdir] and also check that http port 80 opened or not. This process will download the executable for all the font files.
This step will create RPM in /usr/src/redhat/RPMS/noarch/msttcorefonts-1.3-4.noarch.rpm
  • Installing RPM: Change the directory to /usr/src/redhat/RPMS/noarch/ and run the follwing command
# rpm -ivh msttcorefonts-1.3-4.noarch.rpm

  • Restart X server:
/sbin/service xfs restart

Now you can check the newly installed fonts on /usr/X11R6/lib/X11/fonts/TTF
Important Note:  Sometimes you might need to modify the msttcorefonts-1.3-4.spec file  for adding new address of mscorefonts location in sourceforge.net.  If you still face problems downloading font file then you can use my own font RPM [msttcorefonts-1.3-4.noarch.rpm].  You can download and install directly using # rpm -ivh msttcorefonts-1.3-4.noarch.rpm.
Good Luck!

Enjoy new fonts in your Linux machine.

Perl’s hidden treasure (The Schwartzian Transform)

Hello,

If you ask me about the best features of Perl then there will be many answers CPAN, Hashes, RegX etc etc but the one of the hidden feature of perl is The Schwartzian Transform. This is a technique that allows you to efficiently sort by a computed, secondary index.  Let’s say that you wanted to sort a list of strings by their md5 sum.  Pl. see the code below (the comments below are best read from bottom).

my @strings = (‘C’, ‘CPlusPlus’, ‘Java’, ‘Perl’);

my $sorted_strings_on_MD5 =

map { $_->[0] } # map back to the original value

sort { $a->[1] cmp $b->[1] } # sort by the correct element of the list

map { [$_, MD5Calu_func($_)] } #  create a list of anonymous lists

@strings #  take strings

Where MD5Calu_func($_) represents an expression that takes $_ (each item of the list in turn) and produces the corresponding value that is to be compared. This way,  you only have to do the expensive md5 computation N times, rather than N log N times. That’s the beauty of algorithm.

The algorithm has been given by one of the greatest guy is Perl community Randal L. Schwartz.

Happy reading!

Perl Myths

Hello

I am sharing a presentation on Perl Myths directly from author of the Perl DBI module,  Tom Brnce.  He has given a detailed analysis of myths associated with Perl and future of  Perl5/ Perl 6.

[slideshare id=2044080&doc=perl-myths-200909-090922145348-phpapp01]

Enjoy!

Catalyst Perl MVC framework Introduction

See the link below for a excellent intro video on Catalyst MVC framework.

http://www.youtube.com/watch?v=zmm56R0Nqis
http://wiki.dandascalescu.com/howtos/catalyst/introduction_to_catalyst#comment-32571154

The guy has done great job for putting all together. I hope this will help in accelerating Catalyst learning.

I am waiting for more videos on Catalyst like using DBIx::Class, REST controller etc.

Continue reading “Catalyst Perl MVC framework Introduction”