• Home
  • Ajax Jquery and PHP contact form example

Ajax Jquery and PHP contact form example

December 31, 2011 Ning 1 Comment


View demo click here
Download demo


'.$_SESSION['errStr'].'
'; unset($_SESSION['errStr']); } $success=''; if($_SESSION['sent']) { $success='

Thank you!

'; $css=''; unset($_SESSION['sent']); } ?>

We use the $_SESSION array to populate the values of the input fields. This is done to insure that the data is not lost during page redirects, which occur when the form is submitted to submit.php during the regular form submit.

Another important aspect are the classes assigned to the input fields – classs=”validate[required,custom[onlyLetter]]”. These classes are used by the validation plug-in to define the validation rules for every input field, or text area. We are basically saying that the field is required, and only letters are allowed.


jQuery

We are using two jQuery plugins – JQtransform for styling all the form elements, and formValidator, which will help us validate all the input fields on the client side.

It is important to remember to always validate the input data on the server side in addition to client side validation.

First we need to include all the required libraries.





 





The above code is from the head section of index.php. We first include the stylesheets that are used by the two plugins, and then the jQuery library and the plugins. You might find line 5 interesting – this is a special set of CSS rules that we create with PHP to show a confirmation message, as you will see later.

Now lets take a look at our script.js

$(document).ready(function(){
	/* after the page has finished loading */

	$('#contact-form').jqTransform();
	/* transform the form using the jqtransform plugin */

	$("button").click(function(){

		$(".formError").hide();
		/* hide all the error tooltips */
	});

	var use_ajax=true;
	$.validationEngine.settings={};
	/* initialize the settings object for the formValidation plugin */

	$("#contact-form").validationEngine({	/* create the form validation */
		inlineValidation: false,
		promptPosition: "centerRight",
		success :  function(){use_ajax=true},	/* if everything is OK enable AJAX */
		failure : function(){use_ajax=false}	/* in case of validation failure disable AJAX */
	 })

	$("#contact-form").submit(function(e){

			if(!$('#subject').val().length)
			{
				$.validationEngine.buildPrompt(".jqTransformSelectWrapper","* This field is required","error")
				/* a custom validation tooltip, using the buildPrompt method */

				return false;
			}

			if(use_ajax)
			{
				$('#loading').css('visibility','visible');
				/* show the rotating gif */

				$.post('submit.php',$(this).serialize()+'&ajax=1',
				/* using jQuery's post method to send data */

				function(data){
					if(parseInt(data)==-1)
						$.validationEngine.buildPrompt("#captcha","* Wrong verification number!","error");
						/* if there is an error, build a custom error tooltip for the captcha */
					else
					{
						$("#contact-form").hide('slow').after('

Thank you!

'); /* show the confirmation message */ } $('#loading').css('visibility','hidden'); /* hide the rotating gif */ }); } e.preventDefault(); /* stop the default form submit */ }) });

JQuery plugin jqTransform:
This plugin is a jQuery styling plugin wich allows you to skin form elements.
Detail: http://www.dfc-e.com/metiers/multimedia/opensource/jqtransform/

This entire script block is executed within the $(document).ready method, which guarantees that it is run after the page has finished loading.

Next we use the jqTransform() method that is defined by the jqtransform plugin. It converts and styles all of the form’s elements (input fields, text areas, buttons).

The select element is actually replaced by a set of divs and anchors. It surely looks great, but opens up some problems with the validation plugin which make us handle our own tooltip for the select drop-down.

After this on line 7 we bind every click on the buttons at the bottom of the page with a line of code that hides all currently displayed error tooltips by the validation plugin. This insures they are properly refreshed and do not stay on screen if the user enters valid data.

Later we initialize the formValidation plugin with the validationEngine() method and on line 24 define the form’s onsubmit event. A few things worth mentioning here – the custom tooltip on line 28, and the additional ajax=1 parameter on line 39. This parameter is used by submit.php to distinguish whether the request has been made through ajax or directly with the form submit.

Also notice that we use a special variable use_ajax, to prevent ajax interactions if the form fails to validate.


submit

require "phpmailer/class.phpmailer.php";

session_name("fancyform");	/* starting the session */
session_start();

foreach($_POST as $k=>$v)
{
	/* if magic_quotes is enabled, strip the post array */
	if(ini_get('magic_quotes_gpc'))
	$_POST[$k]=stripslashes($_POST[$k]);

	$_POST[$k]=htmlspecialchars(strip_tags($_POST[$k]));
	/* escape the special chars */
}

$err = array();

/* some error checks */
if(!checkLen('name'))
	$err[]='The name field is too short or empty!';

if(!checkLen('email'))
	$err[]='The email field is too short or empty!';
else if(!checkEmail($_POST['email']))
	$err[]='Your email is not valid!';

if(!checkLen('subject'))
	$err[]='You have not selected a subject!';

if(!checkLen('message'))
	$err[]='The message field is too short or empty!';

/* compare the received captcha code to the one in the session array */
if((int)$_POST['captcha'] != $_SESSION['expect'])
	$err[]='The captcha code is wrong!';

/* if there are errors */
if(count($err))
{
	/* if the form was submitted via AJAX */
	if($_POST['ajax'])
	{
		echo '-1';
	}

	/* else fill the SESSION array and redirect back to the form */
	else if($_SERVER['HTTP_REFERER'])
	{
		$_SESSION['errStr'] = implode('
',$err); $_SESSION['post']=$_POST; header('Location: '.$_SERVER['HTTP_REFERER']); } exit; } /* the email body */ $msg= 'Name: '.$_POST['name'].'
Email: '.$_POST['email'].'
IP: '.$_SERVER['REMOTE_ADDR'].'

Message:

'.nl2br($_POST['message']).' '; $mail = new PHPMailer(); /* using PHPMailer */ $mail->IsMail(); $mail->AddReplyTo($_POST['email'], $_POST['name']); $mail->AddAddress($emailAddress); $mail->SetFrom($_POST['email'], $_POST['name']); $mail->Subject = "A new ".mb_strtolower($_POST['subject'])." from ".$_POST['name']." | contact form feedback"; $mail->MsgHTML($msg); $mail->Send(); unset($_SESSION['post']); /* unsetting */ /* the form was successfully sent */ if($_POST['ajax']) { echo '1'; } else { $_SESSION['sent']=1; if($_SERVER['HTTP_REFERER']) header('Location: '.$_SERVER['HTTP_REFERER']); exit; } /* some helpful functions */ function checkLen($str,$len=2) { return isset($_POST[$str]) && mb_strlen(strip_tags($_POST[$str]),"utf-8") > $len; } function checkEmail($str) { return preg_match("/^[\.A-z0-9_\-\+]+[@][A-z0-9_\-]+([.][A-z0-9_\-]+)+[A-z]{1,4}$/", $str); }

Note how we check whether the $_POST[‘ajax’] variable has been set and act accordingly. As you remember, we set it back in script.js to indicate we were using AJAX to fetch the data.

The two $_SESSION variables errStr and post are used to share data between the form and submit.php in case JS is disabled. Here post contains the $_POST array we sent and is used to populate the fields of the form, once the user is redirected back.

With this our fancy contact form is finished!

One Comment

    July 19, 2014 REPLY

    Pretty great post. I simply stumbled upon your weblog and
    wished to mention that I have truly enjoyed surfing around your weblog posts.
    In any case I will be subscribing in your rss feed and I am hoping you write again very soon!

leave a comment

*