Here's how I built my first AJAX widget using Template, Javascript, and CGI::Application. It removes usernames from a list when the user clicks the remove link, without refreshing the page. The hardest part was figuring out how to properly POST using the XmlHttpRequest object. Note that my CGI handler does not return anything in this particular case.
In the template code:
<script type="text/javascript">
var xmlhttp=false;
/*@cc_on @*/
if (!xmlhttp && typeof XMLHttpRequest!='undefined') {
xmlhttp = new XMLHttpRequest();
}
function myfunction(username) {
var params = "rm=remove&username="+username;
var objectlist = document.getElementById(objectlist);
// rm is the node we want to remove from the DOM
var rm = document.getElementById(username);
// The true attribute means the script continues after
// the post has been executed
xmlhttp.open("POST", '/my/runmode/', true);
xmlhttp.setRequestHeader("Content-Type", "application/x-www-form-u
+rlencoded");
xmlhttp.setRequestHeader("Connection","close");
// Connection is to be closed after transfer
xmlhttp.onreadystatechange=function() {
if (xmlhttp.readyState==4) {
// Delete the html node when request is complete
rm.parentNode.removeChild(rm);
}
}
xmlhttp.send(params);
}
</script>
<ul id="objectlist">
[% FOREACH object = objects %]
<p id="[% object.username %]">[% object.username %] -
<a href="#"
onclick="myfunction('[% object.username %]');">
remove</a>
</p>
[% END %]
</ul>
Meanwhile in my CGI::App handler...
sub setup {
my $self = shift;
$self->start_mode('default');
$self->run_modes( [ qw( default remove ) ] );
}
sub remove {
my $self = shift;
my $user =
My::User->retrieve(
username => $self->query->param('username')
);
$user->delete;
}
|