MY mENU


Sunday, 30 September 2012

Create fancy contact form with CSS 3 and jQuery


This tutorial is about creating a simple contact form using XHTML CSS, PHP, and jQuery. The Aim of this article is to show some of the nice CSS 3 style properties such as adding Background Gradient, Corners and Borders to Form Elements.

Step 1 – The HTML Mark Up

The Step 1 is the backbone of the form. It Contains the HTML Code to add textboxes, textarea and a submit Button.
01<form>
02<p>
03<input name="name" type="text" id="name"/>
04<label for="name">Name </label>
05</p>
06<p>
07<input name="name" type="text" id="email"/>
08<label for="email">Email </label>
09 </p>
10<p>
11<input name="website" type="text" id="website"/>
12<label for="website">Name </label>
13 </p>
14<p>
15<textarea name="text"></textarea>
16 </p>
17<p>
18<input value="Send" type="submit" id="Send"/>
19 </p>
20</form>
Step 1 - xHTML Form Backbone

Step 2 – Styling with CSS ( Without CSS3 Properties )

In this step, Basic CSS Style is added to make the form a bit more elegant .Pretty Simple Stuff here, nothing special. The wooden background texture used has been taken from flickR here .
01body { padding:50px 100pxfont:12px Verdana, Geneva, sans-serif;
02background:url("wooden_background.jpg"repeat scroll 0 0 #282828;
03 }
04 
05input, textarea {
06 padding8px;
07 bordersolid 1px #E5E5E5;
08fontnormal 12px VerdanaTahomasans-serif;
09 width200px;
10 
11 }
12 
13textarea {
14 width400px;
15 max-width400px;
16 height150px;
17 line-height150%;
18 }
19 
20.form label {
21 margin-left10px;
22 color#999999;
23 }
24 
25.submit input {
26 widthauto;
27 padding9px 15px;
28 background#617798;
29 font-size14px;
30 color#FFFFFF;
31 cursor:pointer;
32 }
33#form-div {
34background-color:#F5F5F5;
35padding:15px;
36}
37 
38#wrapper {
39margin:30px auto;
40width:500px;
41}
Step 2 : Basic CSS Style

Step 3 -Adding CSS 3 to beautify the Form

We now use some CSS3 Style properties to add some shadow effect , a gradient to the background of each form element and also rounded corners .The thing about Css 3 Property is because it is not the standard and officially yet , so we have to use browser-version CSS3 Property . So for Mozilla we use ,we use the  ‘-moz’ prefix and  for webkit browsers such as safari and chrome we use ‘-webkit’ .
  • Add Shadow Effect
  • 1box-shadow: rgba(0,0,00.10px 0px 8px;/* Default property recognized by some browsers- a Good practice to include it*/
    2-moz-box-shadow: rgba(0,0,00.10px 0px 8px;/*For Mozilla Firefox Browsers*/
    3-webkit-box-shadow: rgba(0,0,00.10px 0px 8px;/*For Webkite browsers - Chrome and Safari*/
    4    
    This CSS Property Takes a color and 3 Length as attribute .
    Color - It can be in Hex/Rgb/Rgba
    Horizontal offset-Positive Value means shadow will be on the right, and a negative value indicates shadow will be on the left.
    Vertical Offset
     -Positive value means shadox will be on the top and a Negative value indicates shadow will be below .
    Blur Radius - The higher the number , the more blurred it will be .
    For this example , i have used RGBA .As compared to RGB , RGBA is simply color with Opacity .
    Syntax for RGBA :
    1rgba[RED][GREEN][BLUE][ALPHA]
    2 
    3/*Alpha  = Opacity*/
  • Add Gradient to Background
  • 1background: -webkit-gradient(linear, left topleft 25, from(#FFFFFF), color-stop(4%#EEEEEE), to(#FFFFFF));/*Chrome and Safari*/
    2 background: -moz-linear-gradient(top#FFFFFF#EEEEEE 1px#FFFFFF 25px);/* Firefox Browsers */
    3background#FFFFFF url('bg_form.png'left top repeat-x;
    4    
    The 3rd one is not a CSS 3 Property .It’s purpose here is to mimic it in browsers like Internet Explorer 6,7,8 since it does not support CSS3 .
  • Add Rounded Corners
  • 1-moz-border-radius:12px 12px 12px 12px;
    2-webkit-border-radius: 12px 12px 12px 12px;
    Unfortunately rounded corners will not be rendered in Internet Explorer .You can go to CurvyCorners to make it work on IE Browsers .
    Step 3 : Form with CSS3 Properties

Step 4-Client Side Validation and Ajax Submission with jQuery

I used the Validation Engine Plug in to add Validation to the form. You can find more about this with. Cedric’s Post .
01$(document).ready(function() {
02 // SUCCESS AJAX CALL, replace "success: false," by:     success : function() { callSuccessFunction() },
03 $("#form1").validationEngine({
04 ajaxSubmit: true,
05 ajaxSubmitFile: "ajaxSubmit.php",
06 ajaxSubmitMessage: "Thank you, We will contact you soon !",
07 success :  false,
08 failure : function() {}
09 })
10 
11});
Step 4 : jQuery Validation Added

Step 5- Sending Mail with PHP

The PHP Code below handles the Email Submission For the online Demo ,the Email Submission has been disabled to prevent abuses. You can download the source code using the download link below to get the full working code.
01//Code Updated on 18 Feb 2011
02 
03$name $_POST['name']; // contain name of person
04$email $_POST['email']; // Email address of sender
05$web $_POST['web']; // Your website URL
06$body $_POST['text']; // Your message
07$receiver "ismaakeel@gmail.com" // hardcorde your email address here - This is the email address that all your feedbacks will be sent to
08if (!empty($name) & !empty($email) && !empty($body)) {
09    $body "Name:{$name}\n\nWebsite :{$web}\n\nComments:{$body}";
10    $send = mail($receiver'Contact Form Submission'$body"From: {$email}");
11    if ($send) {
12        echo 'true'//if everything is ok,always return true , else ajax submission won't work
13    }
14 
15}

Allowing Other Apps to Start Your Activity

The previous two lessons focused on one side of the story: starting another app's activity from your app. But if your app can perform an action that might be useful to another app, your app should be prepared to respond to action requests from other apps. For instance, if you build a social app that can share messages or photos with the user's friends, it's in your best interest to support the ACTION_SEND intent so users can initiate a "share" action from another app and launch your app to perform the action.

To allow other apps to start your activity, you need to add an element in your manifest file for the corresponding element.

When your app is installed on a device, the system identifies your intent filters and adds the information to an internal catalog of intents supported by all installed apps. When an app calls startActivity() orstartActivityForResult(), with an implicit intent, the system finds which activity (or activities) can respond to the intent.

Add an Intent Filter
In order to properly define which intents your activity can handle, each intent filter you add should be as specific as possible in terms of the type of action and data the activity accepts.

The system may send a given Intent to an activity if that activity has an intent filter fulfills the following criteria of the Intent object:

Action

A string naming the action to perform. Usually one of the platform-defined values such as ACTION_SEND orACTION_VIEW.

Specify this in your intent filter with the element. The value you specify in this element must be the full string name for the action, instead of the API constant (see the examples below).

Data

A description of the data associated with the intent.

Specify this in your intent filter with the element. Using one or more attributes in this element, you can specify just the MIME type, just a URI prefix, just a URI scheme, or a combination of these and others that indicate the data type accepted.

Note: If you don't need to declare specifics about the data Uri (such as when your activity handles to other kind of "extra" data, instead of a URI), you should specify only the android:mimeType attribute to declare the type of data your activity handles, such as text/plain or image/jpeg.

Category
Provides an additional way to characterize the activity handling the intent, usually related to the user gesture or location from which it's started. There are several different categories supported by the system, but most are rarely used. However, all implicit intents are defined with CATEGORY_DEFAULT by default.

Specify this in your intent filter with the element.

In your intent filter, you can declare which criteria your activity accepts by declaring each of them with corresponding XML elements nested in the element.

For example, here's an activity with an intent filter that handles the ACTION_SEND intent when the data type is either text or an image:
















Each incoming intent specifies only one action and one data type, but it's OK to declare multiple instances of the, , and elements in each .

If any two pairs of action and data are mutually exclusive in their behaviors, you should create separate intent filters to specify which actions are acceptable when paired with which data types.

For example, suppose your activity handles both text and images for both the ACTION_SEND andACTION_SENDTO intents. In this case, you must define two separate intent filters for the two actions because aACTION_SENDTO intent must use the data Uri to specify the recipient's address using the send or sendto URI scheme. For example:


































Note: In order to receive implicit intents, you must include the CATEGORY_DEFAULT category in the intent filter. The methods startActivity() and startActivityForResult() treat all intents as if they contained theCATEGORY_DEFAULT category. If you do not declare it, no implicit intents will resolve to your activity.

For more information about sending and receiving ACTION_SEND intents that perform social sharing behaviors, see the lesson about Receiving Content from Other Apps.

Handle the Intent in Your Activity

In order to decide what action to take in your activity, you can read the Intent that was used to start it. As your activity starts, call getIntent() to retrieve the Intent that started the activity. You can do so at any time during the lifecycle of the activity, but you should generally do so during early callbacks such asonCreate() or onStart().

For example:

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
// Get the intent that started this activity
Intent intent = getIntent();
Uri data = intent.getData();
// Figure out what to do based on the intent type
if (intent.getType().indexOf("image/") != -1) {
// Handle intents with image data ...
} else if (intent.getType().equals("text/plain")) {
// Handle intents with text ...
}
}

Return a Result

If you want to return a result to the activity that invoked yours, simply call setResult() to specify the result code and result Intent. When your operation is done and the user should return to the original activity, callfinish() to close (and destroy) your activity. For example:

// Create intent to deliver some kind of result data

Intent result = new Intent("com.example.RESULT_ACTION", Uri.parse("content://result_uri");

setResult(Activity.RESULT_OK, result);

finish();


You must always specify a result code with the result. Generally, it's either RESULT_OK or RESULT_CANCELED. You can then provide additional data with an Intent, as necessary.

Note: The result is set to RESULT_CANCELED by default. So, if the user presses the Back button before completing the action and before you set the result, the original activity receives the "canceled" result.

If you simply need to return an integer that indicates one of several result options, you can set the result code to any value higher than 0. If you use the result code to deliver an integer and you have no need to include theIntent, you can call setResult() and pass only a result code. For example:

setResult(RESULT_COLOR_RED);
finish();

In this case, there might be only a handful of possible results, so the result code is a locally defined integer (greater than 0). This works well when you're returning a result to an activity in your own app, because the activity that receives the result can reference the public constant to determine the value of the result code.

Note: There's no need to check whether your activity was started with startActivity() orstartActivityForResult(). Simply call setResult() if the intent that started your activity might expect a result. If the originating activity had called startActivityForResult(), then the system delivers it the result you supply to setResult(); otherwise, the result is ignored.