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) ]