Welcome, Guest :: Blog Home | Login | Register

Articles By Tag:
Jquery Ajax Forms For Catalyst Apps

2009-10-11 16:28:02 Tags: catalyst jquery ajax

I've been working on a private, personal project for a few weeks now and would like to share some simple steps for slick, "in-place" form submissions via Jquery. For an example, you can click on either the "Resume" or "Code Samples" links to the left. Both screens require the user to enter a valid email address in order to view the main content.

The form used for this task will validate input data, submit validated data to a catalyst controller, and then either, depending on the response from the controller, display the main content or show an error. All this is done "dynamically" from the same screen. The main effect of this setup is very much like a native desktop client application, rather than the classic web based application work flow.

In my private (unreleased) application I am taking this process much farther, resulting in an extremely powerful and efficient web base application than runs similar to many desktop applications.

First we set up the jQuery script:

Code:
<script type="text/javascript">

$(document).ready(function(){
  $('#emailLoading').hide();
  $('#saving_settings').hide("fast");
  $('#email_valid').hide("fast");
  
  $('#email').blur(function(){
    $('#emailLoading').show();
    if( !$('#email').val() ) {
      $('#emailResult').html('
<span style="color:#f00;font-weight: bold;font-size:12px;">Required field</span>');
      $('#emailLoading').hide();
    } else {
      $.post("[% Catalyst.uri_for('/formvalidation/email_session') %]", {
	  email: $('#email').val()
      }, function(response){
	if( response == 'FAIL' ) {
	  $('#emailResult').html('
<span style="color:#f00;font-weight: bold;font-size:12px;">E-mail not valid</span>');
	  $('#emailLoading').hide();
	} else {
	  $('#emailResult').html('<img src="[% Catalyst.uri_for('/static/images/accepted.png') %]">
<span style="color:#0c0;font-weight: normal;font-size:10px;">E-mail valid</span>');
	  $('#emailLoading').hide();
	}
      });
    }
  });
  
  $("#email_session").bind('submit', function(event){
    $('#email_form').hide("fast");
    $("#saving_settings").show('fast');
    $.post("[% Catalyst.uri_for('/formvalidation/email_session') %]", {
	email: $('#email').val(),
	store: 1
    }, function(response){
      if( response == 'FAIL' ) {
	$('#email_form').show("fast");
        $("#saving_settings").hide('fast');
	$('#emailResult').html('
<span style="color:#f00;font-weight: bold;font-size:12px;">E-mail not valid</span>');
	$('#emailLoading').hide();
      } else {
	$('#email_valid').show("fast");
        $("#saving_settings").hide('fast');
      }
    });
    return false;
  });
  
});

</script>


Next we setup the form:

Code:
<fieldset>
  <legend>jQuery Catalyst Forms</legend>
  
[% IF Catalyst.session.email.valid %]
  
  <!-- User has access, show protected screen -->
  Main content...
  
[% ELSE %]
  
  <div id="email_form" style="height: 500px;">
    <form id="email_session">
  <table border=0>
    <tr>
      <td colspan=3>Please enter e-mail address to continue:</td>
    </tr>
    <tr>
      <td colspan=3> </td>
    </tr>
    <tr>
      <td><input type="text" name="email" id="email">
          <span id="emailLoading"><img src="[% Catalyst.uri_for('/static/images/loader.gif') %]" alt="..." /></span>
      <span id="emailResult"></span></td>
      <td style="text-align: left;vertical-align: top;"><button id="x_submit">Submit</button></td>
      <td>  </td>
    </tr>
  </table>
    </form>
  </div>
  <div id="saving_settings">Saving Settings <img src=[% Catalyst.uri_for('/static/images/ajax-loader.gif') %]></div>
  
[% END %]
  
  <div id="email_valid">
    <!-- User has access, show protected screen -->
    Main content...
  </div>

</fieldset>


Next we setup a new Catalyst controller, mine is called FormValidation.pm, and add the following code:

Perl Code:
package stephensykes::Controller::FormValidation;

use strict;
use warnings;

use parent 'Catalyst::Controller';

=head1 NAME

stephensykes::Controller::FormValidation - FormValidation Controller

=head1 DESCRIPTION

Used to validate forms via jQuery.

=head1 METHODS

$.post("[% Catalyst.uri_for('/formvalidation/email_session') %]", {
    email: $('#email').val()
}

=cut

=head2 index

=cut

sub email_session : Local {
    my ( $self, $c ) = @_;
    
    my $email = $c->req->param('email');
    my $store = $c->req->param('store');
    
    my $response;
    
    use Email::Valid;
    
    my $email_valid = Email::Valid->address( -address => $email, -mxcheck => 1 );
    
    if( !$email_valid )
    {
        $response = 'FAIL';
    }
    else
    {
        if( $store )
        {
            $c->session->{email}->{valid} = 1;
            
            $c->model('StephenSykesDB::EmailSessions')->create({
                session_id => undef,
                email      => $email_valid,
            });
        }
        
        $response = 'OK';
    }
    
    $c->res->content_type('application/text');
    $c->res->body($response);
}

=head1 AUTHOR

Stephen Sykes

=head1 LICENSE

This library is free software. You can redistribute it and/or modify
it under the same terms as Perl itself.

=cut

1;


It's that simple.

[ Comments (0) ]




OpenBlog Catalyst App \@ GitHub

2009-08-16 18:33:56 Tags: catalyst perl software

The Catalyst MVC driven software OpenBlog is now available as open source project at GitHub.

Here is the public clone URL:
git://github.com/sasykes/OpenBlog.git

Please contact me if you plan to modify or use the software. I am interested to see if anyone would be interested in future use/development.

~Stephen

[ Comments (5) ]




Domain Lister \@ GitHub

2009-08-12 22:01:12 Tags: catalyst perl software

The Catalyst MVC software driven domain name auction/listing software I developed for MySQLSoftware.net is now available as open source project at GitHub.

Here is the public clone URL:
git://github.com/sasykes/Domain-Lister.git

Please contact me if you plan to modify or use the software. I am interested to see if anyone would be interested in future use/development.

~Stephen

[ Comments (0) ]




Free Agent

2009-08-02 15:16:37 Tags: catalyst perl programming work

I'm now a 'free agent' and looking for a Perl programming gig. If you know of any Perl shops that might be hiring, please give me a shout!

Preferences:
1) Catalyst MVC Web Framework based projects.
2) Modern shop.
3) Telecommute.

~Stephen

[ Comments (0) ]




Domain Lister v1.0 - Catalyst MVC Application

2008-04-21 23:14:48 Tags: catalyst perl mvc mysql

I am currently hard at work developing a new domain name auction, well an offer/counter-offer, application for MySQLSoftware.net. This system, powered by the Catalyst MVC Web Framework, will replace my existing domain name auction software. I'll be updating the MySQLSoftware.net website soon with more detailed information regarding the release.

All previous software versions will not be considered deprecated, as I will no longer provide support for them. The new application will require a good bit of maintenance/support to new clients, so there will be a maintenance plan implemented once the new version is ready for deployment.

Stay tuned for further details, including a demo version via FastCGI implementation. Mainly administration features are needing finishing touches, including the ability to generate additional administrator accounts.

Screen Shot:


Regards,
Stephen

[ Comments (0) ]




New Blog Up

2008-04-08 17:57:14 Tags: catalyst perl blog software developer mvc

Spent a good deal of time today coding my new blog for stephensykes.us. I'll probably drop the old OpenBlog application as it was just a learning project for me when I started working with Catalyst MVC.

And since I need to test the code tag, here's some interesting code for your amusement. This is actually part of the soon to be implemented tag cloud feature for my blog.

Perl Code:
# Update TagCloud weight
foreach my $fields_dbic (
    $c->model('StephenSykesDB::ArticleTags')->search(
        article_id => $form->{article_id},
        {
         prefetch  => 'tag_cloud',
         },
    )
) {
    if ($fields_dbic->tag_cloud->weight > 0) {
        # Subtract 1 from weight and update tag cloud
        my $new_weight = ($fields_dbic->tag_cloud->weight - 1);
        $c->model('StephenSykesDB::TagCloud')->update_or_create({
            tag_id => $fields_dbic->tag_cloud->tag_id,
            descr  => $fields_dbic->tag_cloud->descr,
            weight => $new_weight,
        });
    }
}
# Delete all ArticleTags and then add new from form
$c->model('StephenSykesDB::ArticleTags')->search({ article_id => $form->{article_id} })->delete;
    
# Split tags on white space
my @tags = split(/ /, $form->{Tags});

foreach my $tag_rec (@tags) {
    $tag_rec =~ tr/[A-Z]/[a-z]/;
    my $tag_cloud_dbic = $c->model('StephenSykesDB::TagCloud')->find({ descr => $tag_rec });
    if ($tag_cloud_dbic) { # update existing tag
        my $new_weight = ($tag_cloud_dbic->weight + 1);
        $c->model('StephenSykesDB::TagCloud')->update_or_create({
            tag_id => $tag_cloud_dbic->tag_id,
            descr  => $tag_cloud_dbic->descr,
            weight => $new_weight,
        });
        # Add tags to site_tags table
        $c->model('StephenSykesDB::ArticleTags')->create({
            article_id => $form->{article_id},
            tag_id     => $tag_cloud_dbic->tag_id,
        });
    } else { # create new tag
        $c->model('StephenSykesDB::TagCloud')->create({
            tag_id => undef,
            descr  => $tag_rec,
            weight => '1',
        });
        # Get new tag_id
        my $tag_dbic = $c->model('StephenSykesDB::TagCloud')->find({ descr => $tag_rec });
        # Add tags to site_tags table
        $c->model('StephenSykesDB::ArticleTags')->create({
            article_id => $form->{article_id},
            tag_id     => $tag_dbic->tag_id,
        });
    }
}


[ Comments (0) ]