You are here: Home / WebDev / JQuery / Creating Contact Form using FancyBox 2 with Ajax by iAPDesign.com
Themeforest - Site Templates, Web and CMS Themes

Creating Contact Form using FancyBox 2 with Ajax by iAPDesign.com

Hi Guys, Today i will teach you on how to create a simple stylish contact form using FancyBox 2 with Ajax from fancyapps.com. I hope you learn from this post.


Fancybox? What was that?

FancyBox is a tool that offers a nice and elegant way to add zooming functionality for images, html content and multi-media on your webpages. It is built at the top of the popular JavaScript framework jQuery and is both easy to implement and a snap to customize. excerpts from fancyapps.com

FINAL OUTPUT: Creating Contact Form using FancyBox 2 with Ajax by iAPDesign.com

Creating Contact Form Using FancyBox 2 With Ajax By IAPDesign.Com

Creating Contact Form Using FancyBox 2 With Ajax By IAPDesign.Com


Demo - Creating Contact Form using FancyBox 2 with Ajax by iAPDesign.com

Alright, Let’s get started.

STEP 1

The first step is create your html markup. So this markup is the starting point of your html it includes, the title, head, body and corresponding closing tags. This is basic html template.


<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<meta name="viewport" content="width=device-width" />
<title>Contact Form Using CSS3 and FancyBox 2 from iAPDesign</title>
</head>
<body>
<!-- YOUR CONTACT FORM WILL SHOW HERE-->
</body>
</html>


STEP 2

After you create your html basic template, insert this line of code inside the body tag of your html. If you view this in your browser you will see a simple contact form page with no CSS design.

If you notice the link target of our link Show Contact Form is #show_our_contact_form it is because the form that we want to show inside the fancybox is the content of div #show_our_contact_form.


<h1>Creating Contact Form using FancyBox 2 with Ajax by iAPDesign.com</h1>
</p>

<div class="linkhere">
<br/><br/><br/>
<h3>Click the link below to test your Contact Form</h3>
<a href="#show_our_contact_form" id="contact_us">Show Contact Form</a>
</div>
<div id="show_our_contact_form">
<h3>Send us Message / Feedback / Comment / Suggestions!</h3>
<p><span class="errormsg"></span></p>

<label for="name">* Name </label>
<p>
<input name="fname" type="text" id="name" minlength="4" maxlength="15" required/>
</p>

<label for="email">* Email </label>
<p>
<input name="email" type="text" id="email" required/>
</p>

<label for="message">* Message</label>
<p>

<textarea name="messages" id="message" minlength="2" required></textarea>

</p>
<p>
<input value="Send Message" type="button" id="send_form"/> 
</p>

</div>


STEP 3

In this step, we will define our custom style or CSS (Cascading Style Sheet). From the root folder within your index.html file,create a folder and name it css inside of that folder create a file name style.css. Open the file and insert this css code that we created.


@charset "utf-8";
/* CSS Document */

body, div, h1, form, fieldset, input, textarea {
	margin: 0; padding: 0; border: 0; outline: none;
}

html {
	height: 100%;
}

body { padding:50px 100px; font:12px Verdana, Geneva, sans-serif;
background-color: #E6EBF4;

 }

input, textarea {
	padding: 8px;
	border: solid 1px #E5E5E5;
	font: normal 13px Verdana, Tahoma, sans-serif;
	width: 200px;
	background: -webkit-gradient(linear, left top, left 25, from(#FFFFFF), color-stop(4%, #EEEEEE), to(#FFFFFF));
	background: -moz-linear-gradient(top, #FFFFFF, #EEEEEE 1px, #FFFFFF 25px);
	box-shadow: rgba(0,0,0, 0.1) 0px 0px 8px;
	-moz-box-shadow: rgba(0,0,0, 0.1) 0px 0px 8px;
	-webkit-box-shadow: rgba(0,0,0, 0.1) 0px 0px 8px;
}

textarea {
 width: 400px;
 max-width: 400px;
 height: 150px;
 line-height: 150%;
 }

.form label {
 margin-left: 10px;
 color: #999999;
 }

input:hover,textarea:hover {
 box-shadow: 0 0 1px #000;
}

#send_form{
	color: #fef4e9;
	border: solid 1px #da7c0c;
	background: #f78d1d;
	background: -webkit-gradient(linear, left top, left bottom, from(#faa51a), to(#f47a20));
	background: -moz-linear-gradient(top,  #faa51a,  #f47a20);
}

#send_form:hover {
	background: #f47c20;
	background: -webkit-gradient(linear, left top, left bottom, from(#f88e11), to(#f06015));
	background: -moz-linear-gradient(top,  #f88e11,  #f06015);

}
#send_form:active {
	color: #fcd3a5;
	background: -webkit-gradient(linear, left top, left bottom, from(#f47a20), to(#faa51a));
	background: -moz-linear-gradient(top,  #f47a20,  #faa51a);
	
}

#form-div {
background-color:#F5F5F5;
padding:15px;
}

#show_our_contact_form {
margin:30px auto;
width:450px;
display: none;

}

.errormsg,label,#contact_us{
	color: #f78d1d;
}

#fancybox-wrap {
  margin: -70px 0 0 290px;
}
.fancybox-custom .fancybox-skin {
			box-shadow: 0 0 50px #222;
}


STEP 4

Now to link this style.css into your html template, add this line of code inside the head tag.


<!-- Add our CSS stylesheet -->
<link href="css/styles.css" rel="stylesheet" type="text/css"/>


STEP 5

We setup already our html form so now let’s get started the magic. Download the fancybox javascript from their website fancyapps. After you downloaded the javascript file, the first thing to do is to link the stylesheet of fancybox and the fancybox js file.


<!-- Add fancyBox main CSS files -->
<link rel="stylesheet" type="text/css" href="lib/jquery.fancybox.css?v=2.1.2" media="screen" />

After adding the fancybox.css, Add the fancybox.js and jquery-1.8.2.min.js file before the closing of body tag. We put it here because we want to load this javascript after all the html and images loaded.


<!-- Add our Jquery 1.8.2 -->
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>

<!-- Add Fancybobx JS File -->
<script type="text/javascript" src="lib/jquery.fancybox.js?v=2.1.3"></script>


STEP 6

We are ready now to configure our contact us form to make it functional using fancybox 2. Copy this line of code to initialize the fancybox plugin. Initially our contact form is hidden because in our css it has code block of display:none.


<script type="text/javascript">
$(document).ready(function(){
               <!--contact us is the id name of ourShow Contact Form link -->
		$("#contact_us").fancybox({
			type     :"inline",
			closeBtn :true
		});
		
	});
</script>


STEP 7

Create now a function for validating the email if it is valid or not. Well, there are so many ways to detect the valid email but for now we will use the native way of validating an email using regex in javascript.

This line of code will return true if the email is valid and if not it will return false.


STEP 8

So now let’s do some Ajax so that your contact us form will email if you hit the submit button. Copy this line of code.


$("#send_form").click(function(){	
		
		var name 	= $("#name").val();
		var email 	= $("#email").val();
		var message = $("#message").val();
		
			if( (name == "") || (email == "") || (message == "")){
				$(".errormsg").html(" * All fields Required").fadeIn("Slow").fadeOut(3000);
			}else if(!isValidEmailAddress(email)){
				$(".errormsg").html(" * Invalid Email").fadeIn("Slow").fadeOut(3000);
			} else{
				$(".errormsg").fadeOut();
				$.ajax({
					type	:'POST',
					url		:'php/process.php',
					data	:{	'name' 	 : name,
								'email'	 : email,
								'message': message,
							 },
					beforeSend: function(){
						$("#show_our_contact_form").empty().html("<h3>Sending your Message to our Awesome Boss! Please wait . . . </h3>");
					},
					error:function(){
						alert("Something went wrong!");
					},
					success:function(returnData){
						$("#show_our_contact_form").empty().html("<h3>Your Message Successfully Delivered! <br/> Thank you</h3>");
						window.location.reload();
						
					}
				});
			}
			
	});

Explanation of the code:

  • $(“#send_form”) – This is the id name of our submit button, we used this to check if the user click the submit button and fill up all the required filled.
  • Validation – we validate each filled like the name,email message if they are not empty. If empty or null we will return a message “* All fields Required”
  • Ajax – is Asynchronous JavaScript and XML it is a way of requesting data from the server back to the client browser without loading the page.

Ajax is compose of 6 parts,they are the ff:

  • type – this is either GET or POST it’s like method when your submitting the normal form in html
  • url – path of your php file where you want to request data or to send the data accumulated.
  • data – collection of data that you will submit to the server.
  • beforeSend function() – this is optional, you can define your function here and run that code before submitting the data to the server.
  • error function() – All the error within the submission of the data will occur here.
  • success – Success function is where the data will be returned by the web server and you can manipulate the data inside of it.


STEP 8

Additional, to send the form we will used the mail() in php. If you tried this in your localhost you need to setup your SMTP server locally or if you put it in your server it will work as expected because it is configured already with your web hosting company.

Create a folder name it php inside of that folder create a file name process.php and paste this code.

Note *: “In this php file i setup this code so that it will send it to your email, I mean it will send to the email that you put in the email text box, if you want to change it change the $to with your own email”.


<?php

if(isset($_SERVER['REQUEST_METHOD']) && !empty($_SERVER['REQUEST_METHOD'])){

	$nameSender      = $_REQUEST['name']; 	// this is the sender name
	$emailSender     = $_REQUEST['email'];	// Valid Email
	$message 	 = $_REQUEST['message']; // Message content of what you will send in this form

	$to      	 = $emailSender;
	$subject 	 = 'Simple Contact Form by iAPDesign';

	$headers   = array();
	$headers[] = 'MIME-Version: 1.0';
	$headers[] = 'Content-type: text/plain; charset=iso-8859-1';
	$headers[] = "From: $nameSender <$emailSender>";
	$headers[] = "Subject: $subject";

	mail($to, $subject, $message, implode("\r\n", $headers));

}

?>


CONCLUSION

So that’s it. We are done. You already know how to use the fancybox version 2. And if you have some questions or error encounter just drop by a comments and i’ll try to answer it all for you guys.

SHARE THIS POST AND LIKE OUR FAN PAGE.
iAPDESIGN FACEBOOK FAN PAGE

Codecanyon - PHP,JS,JAVA AND .NET Themeforest - Site Templates, Web and CMS Themes

About Anthony Pillos

I am Anthony Pillos 22 years old from Philippines. I'm the founder of iapdesign website. I am working as a web developer/web designer. This is my life and my passion.

12 comments

  1. Ghanshyam Sharma

    how get i password

  2. Hi, very great work. I’m trying to add this form in my site but I would change the position of .errormsg and put it near “Send Message”. How can I do it?

    • Well you can position the .errormsg class . It’s a just inside with a

      tag.. just place the
      html tag something like this.

      <p><span class="errormsg" style="display: none;"> * All fields Required</span></p>
      <p><input value="Send Message" type="button" id="send_form"></p></code>
      
  3. Thank you very much friend!

  4. Hi dudes,

    how to show without click function display fancybox contact form in my website ?

    • Do you mean auto loading the fancybox contact form when someone visit your website?.. If that’s what you mean..
      One way to do that is to used a .trigger(‘click’) inside $(document).ready()
      So in my codes you can do something like this.
      $("#contact_us").fancybox({
      type :"inline",
      closeBtn :true
      }).trigger('click');

  5. Hi buddy, It is a great job.

    I have a question.

    I am trying to adapt your scripts to my own needs.

    I am using your script to recover a password if the user forgot it.
    How could could it be possible to verify if the email exists in the database. If it doesn’t exist the server should return in the error message “The email provided does not exist in the database, please verify it” else I send an email with the password to the user.

    In advanced thank you

    • Hello…

      Well, what you can do is to is to check from the database first.. if that email exists…
      So its like, when the user click the send button.. in your php script..

      validate email, from database…
      if email exist
      send email function here
      else
      return json_encode(array(‘email_not_exist’ => ‘The email provided does not exist in the database, please verify it’))

      once you you get a json_encode response from ajax..
      you can parse it from your ajax request….
      then show it in an html…

      well that’s it.. I hope you got an idea… let me know if you need some help.. thank you.

Leave a Reply

Your email address will not be published. Required fields are marked *

*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>

Close
Please support the site
By clicking any of these buttons you help our site to get better

Twitter

Facebook

Google+