• RSS
  • Facebook
  • Twitter
Comments

http://tutorialzine.com
Created by Martin Angelov on Apr 7th, 2010
Today we are making a carbon fiber – style form, build using progressive enhancement. This means that we first ensure that the form works well without JavaScript and fancy CSS support (think of IE6 here) and later move on by layering over cool styling, AJAX and jQuery magic.
The form features its own custom tooltip validation, and is even perfectly usable with JavaScript disabled.

Step 1 – XHTML

The first step includes creating the XHTML backbone of the form. It has to be simple, and, according to the principles defined by progressive enhancement, must be perfectly usable by itself.

demo.html

01<div id="carbonForm">
02    <h1>Signuph1>
03
04    <form action="submit.php" method="post" id="signupForm">
05
06        <div class="fieldContainer">
07            <div class="formRow">div>
08            
09        div>
10
11        <div class="signupButton">
12            <input type="submit" name="submit" id="submit" value="Signup" />
13        div>
14
15    form>
16div>
The carbonForm div is the main container for the form. It is centered in the middle of the page with the CSS margin property, and then centered vertically with jQuery (take a look at our MicroTut for more info about centering).
Inside it we have the heading and the form with the fieldContainer div. Inside it there are three formRow divs, which share the markup given below:

demo.html

1<div class="formRow">
2    <div class="label">
3        <label for="name">Name:label>
4    div>
5
6    <div class="field">
7        <input type="text" name="name" id="name" />
8    div>
9div>
Each pair of label and input elements is positioned inside its own wrapping divs, which are floated to the left. This allows for the layout of the form you can see in the demonstration page. It is important to have the text box names the same as their ids, because this is used to display the error tooltips as you will see in the next steps.
Carbon Fiber Signup Form
Carbon Fiber Signup Form

Step 2 – CSS

The form relies heavily on CSS to achieve the carbon fiber effect. A number of CSS3 rules are used as well, which successfully mimic the effects previously possible only in graphic suites as Photoshop. Only the most interesting styles are given here, you can see the rest in styles.css in the download archive.

styles.css

01#carbonForm{
02    /* The main form container */
03    background-color:#1C1C1C;
04    border:1px solid #080808;
05    margin:20px auto;
06    padding:20px;
07    width:500px;
08
09    -moz-box-shadow:0 0 1px #444 inset;
10    -webkit-box-shadow:0 0 1px #444 inset;
11    box-shadow:0 0 1px #444 inset;
12}
13
14.fieldContainer{
15    /* The light rounded section, which contans the fields */
16    background-color:#1E1E1E;
17    border:1px solid #0E0E0E;
18    padding:30px 10px;
19
20    /* CSS3 box shadow, used as an inner glow */
21    -moz-box-shadow:0 0 20px #292929 inset;
22    -webkit-box-shadow:0 0 20px #292929 inset;
23    box-shadow:0 0 20px #292929 inset;
24}
25
26#carbonForm,.fieldContainer,.errorTip{
27    /* Rounding the divs at once */
28    -moz-border-radius:12px;
29    -webkit-border-radius:12px;
30    border-radius:12px;
31}
32
33.formRow{
34    height:35px;
35    padding:10px;
36    position:relative;
37}
38
39.label{
40    float:left;
41    padding:0 20px 0 0;
42    text-align:right;
43    width:70px;
44}
45
46label{
47    font-family:Century Gothic,Myriad Pro,Arial,Helvetica,sans-serif;
48    font-size:11px;
49    letter-spacing:1px;
50    line-height:35px; /* Neat line height trick */
51}
52
53.field{
54    float:left;
55}
56
57.field input{
58    /* The text boxes */
59    border:1px solid white;
60    color:#666666;
61    font-family:Arial,Helvetica,sans-serif;
62    font-size:22px;
63    padding:4px 5px;
64    background:url("img/box_bg.png") repeat-x scroll left top #FFFFFF;
65    outline:none;
66}
67
68#submit{
69    /* The submit button */
70    border:1px solid #f4f4f4;
71    cursor:pointer;
72    height:40px;
73    text-indent:-9999px;
74    text-transform:uppercase;
75    width:110px;
76
77    background:url("img/submit.png") no-repeat center center #d0ecfd;
78
79    -moz-border-radius:6px;
80    -webkit-border-radius:6px;
81    border-radius:6px;
82}
83
84#submit.active{
85    /* Marking the submit button as active adds the preloader gif as background */
86    background-image:url("img/preloader.gif");
87}
88
89input:hover,
90input:focus{
91    /* CSS3 glow effect */
92    -moz-box-shadow:0 0 8px lightblue;
93    -webkit-box-shadow:0 0 8px lightblue;
94    box-shadow:0 0 8px lightblue;
95}
Most of these rules are pretty straightforward. You may find interesting how we handle the submit button, as this element is quite tricky to style consistently cross-browser.
To hide the text of the button (in our case “Signup“), we can use the negative text-indent trick, but in IE it only works if we also specify the text-transform:uppercase rule. We also add a transparent background image consisting of the text “Submit” in Century Gothic, which is replaced with a rotating gif preloader if the button is assigned an “active” class.
We also use a number of CSS3 effects along with their vendor-specific versions for better compatibility. border-radius is for rounded corners, and with box-shadow we can mimic different glow and shadow effects.
CSS3 Rounded Corners & Glow
CSS3 Rounded Corners & Glow

Step 3 – jQuery

After including the jQuery library and our own script.js file in the page, we can move on to writing the JavaScript code that will breathe some life into the form.

script.js

01$(document).ready(function(){
02    // $(document).ready() is executed after the page DOM id loaded
03
04    // Binding an listener to the submit event on the form:
05    $('#signupForm').submit(function(e){
06
07        // If a previous submit is in progress:
08        if($('#submit').hasClass('active')) return false;
09
10        // Adding the active class to the button. Will show the preloader gif:
11        $('#submit').addClass('active');
12
13        // Removing the current error tooltips
14        $('.errorTip').remove();
15
16        // Issuing a POST ajax request to submit.php (the action attribute of the form):
17        $.post($('#signupForm').attr('action'),
18            $('#signupForm').serialize()+'&fromAjax=1',function(response){
19
20            if(!response.status)
21            {
22                // Some kind of input error occured
23
24                // Looping through all the input text boxes,
25                // and checking whether they produced an error
26                $('input[type!=submit]').each(function(){
27                    var elem = $(this);
28                    var id = elem.attr('id');
29
30                    if(response[id])
31                        showTooltip(elem,response[id]);
32                });
33            }
34            else location.replace(response.redirectURL);
35
36            $('#submit').removeClass('active');
37        },'json');
38
39        e.preventDefault();
40    });
41
42    $(window).resize();
43});
44
45// Centering the form vertically on every window resize:
46$(window).resize(function(){
47    var cf = $('#carbonForm');
48
49    $('#carbonForm').css('margin-top',($(window).height()-cf.outerHeight())/2)
50});
51
52// Helper function that creates an error tooltip:
53function showTooltip(elem,txt)
54{
55    // elem is the text box, txt is the error text
56    $('
').html(txt).appendTo(elem.closest('.formRow'));
57}
Clicking the submit button (or pressing the enter key while entering text in one of the fields) submits the form. The function that is bound to the submit event prevents this from happening with e.preventDefault() and issues an AJAX request to submit.php instead.
The response that is returned is evaluated as JSON code (a JavaScript object), which contains a special status property. Depending on its value, the script either shows error tooltips on the fields, or redirects the browser to the specified URL in the response.

sample error response

1{
2    "status"    : 0,    // Indicates that the response is an error
3    "email"     : "Please fill in a valid email!",      // Error message
4    "pass"      : "Please fill in a valid password!"    // Error message
5}
The error tooltips are generated by the script while looping though all the fields in the form and checking whether their ids exist as properties in the response object. If they do, a tooltip is created with the showTooltip() function.
Also notice how we use the serialize() method on line 18 to send all the form fields at once. Also, on this same line, we set fromAjax=1, which is going to tell PHP to return the response as JSON.
Now lets see how this response is generated and how the form is validated.
Dynamically Inserted Error Tooltips
Dynamically Inserted Error Tooltips

Step 4 – PHP

The good thing about this form is that it is usable even if JavaScript is disabled. This works, because the action attribute of the form element is also set to submit.php. This means that we only have to implement the validation once no matter how the form is sent.

submit.php

01// Error reporting:
02error_reporting(E_ALL^E_NOTICE);
03
04// This is the URL your users are redirected,
05// when registered succesfully:
06
08
09$errors = array();
10
11// Checking the input data and adding potential errors to the $errors array:
12
13if(!$_POST['name'] || strlen($_POST['name'])<3 || strlen($_POST['name'])>50)
14{
15    $errors['name']='Please fill in a valid name!
Must be between 3 and 50 characters.'
;
16}
17
18if(!$_POST['email'] || !preg_match("/^[\.A-z0-9_\-\+]+[@][A-z0-9_\-]+([.][A-z0-9_\-]+)+[A-z]{1,4}$/", $_POST['email']))
19{
20    $errors['email']='Please fill in a valid email!';
21}
22
23if(!$_POST['pass'] || strlen($_POST['pass'])<5)
24{
25    $errors['pass']='Please fill in a valid password!
Must be at least 5 characters long.'
;
26}
27
28// Checking whether the request was sent via AJAX
29// (we manually send the fromAjax var with the AJAX request):
30
31if($_POST['fromAjax'])
32{
33    if(count($errors))
34    {
35        $errString = array();
36        foreach($errors as $k=>$v)
37        {
38            // The name of the field that caused the error, and the
39            // error text are grouped as key/value pair for the JSON response:
40            $errString[]='"'.$k.'":"'.$v.'"';
41        }
42
43        // JSON error response:
44        die ('{"status":0,'.join(',',$errString).'}');
45    }
46
47    // JSON success response. Returns the redirect URL:
48    echo '{"status":1,"redirectURL":"'.$redirectURL.'"}';
49
50    exit;
51}
52
53// If the request was not sent via AJAX (probably JavaScript
54// has been disabled in the visitors' browser):
55
56if(count($errors))
57{
58    echo '

'.join('

'
,$errors).'

';
59    exit;
60}
61
62// Directly redirecting the visitor if JS is disabled:
63
64header("Location: ".$redirectURL);
All the encountered errors are added to the $errors array. This, depending on whether fromAjax was set or not,  is later returned either as a JSON object, or directly printed to the screen.


Postado por Fernando Schimit - Fox Creative

Leave a Reply