Make Xajax-PHPMailer Contact Forms Work

Post image of Make Xajax-PHPMailer Contact Forms Work
Filed in Web Development 15 comments

I was recently working on design customization of start-up web solutions firm New Media Kreatives. I came across plenty of resources while looking to integrate a simple, yet secure, effective and stylish contact form. But the one that caught my eye was a tutorial by FinalWebsites. However, the codes provided there did not work out of the box and it was only after certain tweaks that I could get the form to function.

Since working contact forms are a regular requirement for web designers and developers I decided to put up a tutorial on how to make a PHPMailer-Xajax contact form work.

First of all, take a look at the New Media Kreatives website. You can see the contact form at the bottom of the homepage itself  under “Quick Contact”.

New Media Kreatives

How It Works

  1. In the above form, all the fields are required. So if you choose to click the submit button without filling up the form, or leave any field empty – the form remains in place and an error message saying “Please fill up all fields.” is displayed below the form.
  2. The form involves a valid email checker. So if you do not fill up a valid email, i.e. there’s no “@” or “.” it again displays an error message “The entered e-mail address is not valid.” and the form remains in place.
  3. If everything is filled up properly and submitted, the form disappears and a success message is displayed in it’s place.

Please note that this tutorial will follow the way I have integrated the form for New Media Kreatives. You can add / delete / modify your own fields.

Make It Work

Firstly, we need the Xajax libraries. Xajax is a powerful PHP Class library which makes it possible to execute PHP scripts using Javascript and XML.

Click here to download the Xajax 0.5 rc1 Compiled. This version would be good for us. Unzip the contents and put them in a directory. Name the directory “xajax”.

The other script required to make this form work, and the most important one, is the PHPMailer. It is a pretty popular and powerful script that enables mail sending via SMTP, sendmail, Qmail or the PHP mail function.

Click here to download the PHPMailer-ML_v1.8.1_core. This version would be good for us. Unzip the contents. Go to “/_acp-ml/modules” directory. You will find the “phpmailer” directory there. Copy the “phpmailer” directory and put it in the same place with your xajax directory.

Now let us create a file named mail.php in the same location where your xajax and phpmailer directories are located. This file will contain your form html, variables and functions.

You can use notepad or your favorite text editor for this purpose. I use Dreamweaver.

The first two lines of this file will essentially function to include the class.phpmailer.php and xajax.inc.php

The class.phpmailer.php is stored in the phpmailer directory while the xajax.inc.php is located in the xajax/xajax_core/ directory. So copy the following lines and paste them at the very beginning of your mail.php file.

// Snippet-1
<?php
require_once('phpmailer/class.phpmailer.php');
require_once('xajax/xajax_core/xajax.inc.php');

Note that we have not closed the php tag. We’ll surely close it at the end when all the codes are in place.

Next we need to create your form and store them inside a variable. We need to do so since we want to make the form disappear or rather, hide the form once the message is successfully sent. Let’s name this variable $form. Copy the following code and place it below the lines mentioned above.

// Snippet-2
$form = '<form id="ContactForm">
            <div class="container">

		<label class="contactlabel">Enter Your Name:<br /><input name="name" type="text" class="input" /></label>
		<label class="contactlabel">Enter Your E-mail:<br /><input name="email" type="text" class="input" /></label>
		<label class="contactlabel">Enter Your Phone:<br /><input name="phone" type="text" class="input" /></label>
		Enter Your Message:<br />
		<textarea name="msg" cols="1" rows="1"></textarea><br />
	        <input type="button" id="subbtn" class="btn" value="Submit" onclick="xajax_myFunction(xajax.getFormValues(\'ContactForm\'));" />

		<div id="form_msg"></div> //this div will contain error messages

	   </div>
	</form>';

Note that we have created a few ids and classes. We’ll stylize them later with CSS. Also note that we have created a blank div with the id “form_msg”. This div displays the errors as they appear. This is a basic form with name, email, phone and message field. Do not forget to mention the “name” for each input fields as these names would be used by the mailer function later on.

Now we need to create a function that would be executed when the submit button is clicked. This function will typically do -

  • Create a new Xajax response
  • Perform field validations i.e. display an error if any field is missing or the email is not valid
  • Create the PHPMailer object and define the required variables
  • Send the email message
  • Hide the form and display a message if the mail is sent successfully

So now copy the codes below and paste it in the mail.php file after the codes mentioned above.

// Snippet-3
function myFunction($get) {  // define the function
    global $form, $error;
    $error = '';
    $objResponse = new xajaxResponse(); // create new xajax response
    $show_form = true;  // display the form
    if (!empty($get['email']) && !empty($get['phone']) && !empty($get['msg']) && !empty($get['name'])) { // checks if any field is empty
        if (preg_match("/^[\w-]+(\.[\w-]+)*@([0-9a-z][0-9a-z-]*[0-9a-z]\.)+([a-z]{2,4})$/i", trim($get['email']))) { // checks for valid email
            $email = preg_replace("/\r\n/", "", $get['email']);
            $from = preg_replace("/\r\n/", "", $get['name']);
  	    $name = $get['name'];
            $phone = $get['phone'];
	    $msg = $get['msg'];
	    $mail = new PHPMailer();
            $mail->IsSMTP();
            $mail->Host = "smtp.yourserver.com";
            $mail->SMTPAuth = true;
            $mail->Username = "username";
            $mail->Password = "password";
            $mail->From = $get['email'];
            $mail->FromName = $get['name'];
            $mail->AddAddress("email@youremail.com");
            $mail->AddReplyTo($email, $from);
            $mail->Subject = "Your Subject";
            $mail->IsHTML(true); // displays html
	    $mail->Body = "Name: $name <br/> Email: $email <br/> Phone: $phone <br/> Message: $msg"; //generates the mail body
            if ($mail->Send()) {
                $error = "Success! Thanks for your interest. We'll contact you shortly."; // message for successful email
                $show_form = false; // form gets hidden
            } else {
                $error = "There was a problem while sending the mail, please try again."; // error message
				$show_form = true; // form is not hidden
            }
        } else {
            $error = "The entered e-mail address is not valid."; // invalid email error message
			$show_form = true; // form is not hidden
        }
    } else {
        $error = "Please fill up all fields."; // missing fields error message
		$show_form = true; // form is not hidden
    }
    if (!$show_form) {
		$objResponse->assign('contact_result', 'innerHTML', $error); // form gets replaced with success message
		} else {
		$objResponse->assign('form_msg', 'innerHTML', $error); // error message displayed in form_msg div
		}
    return $objResponse;
}

Take a good look at the code above. We create a function called myFunction and a new xajax response. The code in line 6 checks for the required fields. In this case all the fields are required. In case your form does not have a phone number field, delete the part

!empty($get['phone']) &&

or add a new field by copying this value and replacing the ‘phone’ with any other field name. In this reference if you are not using the Phone field you should also remove line 11 and any other reference to the variable $phone. Similarly if you want to add a new field, you should add it the way $phone is placed.

Provide your SMTP server in line 15
Provide your mail username in line 17
Provide your mail password in line 18
Provide your email address where you want the mails to be delivered in line 21
Provide the subject you want to be displayed in line 23
Line 25 defines how your emails would look when someone contacts you through the contact form. In this case it would look like

Name: Sender’s Name
Email: Sender’s Email
Phone: Sender’s Phone
Message: Message details

The next few lines in the code above decides what to do with the result of the mail function. If the mail is successfully sent, the entire form – which will be later enclosed in a div called “contact_result” – would be hidden and a success message will be displayed. If not, the blank div we already created within the form would become active, the form will remain visible and the error message will be displayed in the div. You can check out the comments I made inside the code to know which snippet does what.

Now comes the final part of the mail.php file. This part will instantiate the xajax object, register the PHP functions you want to call through xajax and ask xajax to handle requests before the script sends an output.

Copy these final lines and paste it below the codes given above.

// Snippet-4
$xajax = new xajax(); // instantiate the xajax object
$xajax->registerFunction('myFunction'); // register the PHP functions you want to call through xajax
$xajax->processRequest(); //ask xajax to handle requests before the script sends an output.
?>

Note that we end the php tag here. So all the snippets 1 to 4 provided above, together make up the mail.php file.

Cool, so now we have our main function ready. But these functions need to be placed before any HTML code i.e. even before the DOCTYPE. If you are using a header.php as template then you need to PHP include the mail.php file just once, or else you need to include this file before the HTML header beginning of the page(s) you want the form to be displayed and functioned. Do it like this -

<?php include("mail.php"); ?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" ...etc.

So the mail.php file is being called even before the DOCTYPE.
Now we need to tell xajax to generate the necessary javascripts. We do this by adding the following code within the head tags of your header.php or the page(s) you want the form to be displayed and functioned.

<head>
<?php $xajax->printJavascript('xajax/'); ?>
</head>

Once done, we are ready to place the form wherever we want to. We do this through a PHP echo that displays the variable $form within a div called “contact_result”. Once the mail is successfully sent, the entire content of this div i.e. the form will be replaced with the success message. Here’s how to do that -

<?php echo '<div id="contact_result">'.$form.'</div>'; ?>

Great, so now that all is set, we need to stylize our forms with CSS. Just add your styles to the following ids and classes -

#ContactForm {
}
.container {
}
#contact_result {
}
.contactlabel {
}
.input {
}
textarea {
}
.btn {
}
#form_msg {
}

Define your styles within the {} braces and you’re all set to use your new Xajax and PHPMailer based contact form.

Posted by Ranadeep   @   10 January 2010 15 comments
Tags : , , , ,

Share This Post

RSS Digg Twitter StumbleUpon Delicious Technorati

15 Comments

Comments
Jan 10, 2010
1:17 pm

Hi,
Nice tutorial, but I don’t understand why you say that the tutorial code on finalwebsites doesn’t work. I use the code on X websites without any trouble. Sure the code is not complete for a newbie but if you know how XAJAX works it’s not a problem.
Because the tutorial is based on an older Xajax version I posted the updated code to the forum:
http://www.finalwebsites.com/forums/topic/phpxajax-contact-form-upgrade

Maybe I should add that link to the tutorial as well :)

Author Jan 10, 2010
5:56 pm
#2 Ranadeep :

Thanks for coming by.

In the old post $xajax->processRequests() had an issue.

I also needed to tweak a few variables in the new code e.g. $show_form since without the tweak it would not display error messages.

I agree it could have been easy for Xajax Pros, but this tutorial here is intended to enable everyone willing to use the form.

Jan 12, 2010
3:36 pm

Hi,
I really liked your blog! you are a very talented person
Regards,
Viny

Jan 12, 2010
4:45 pm

it’z very usefull information. but i expect more details..
Mical

Jan 12, 2010
11:54 pm

Hi,

Really Fantastic post, i found this post from my technorati Account Top Upcomming News field section. looks like a great blog you have. keep it up.

Kelly

Jan 16, 2010
2:10 am

Thanks for the article. Thanks for sharing your thoughts and article. I rarely post comment…

If I want to get a hold of you, what would be the best way to get in touch? I’d love to run some ideas by you one of these days…related to the acn marketing video phone project I am working on. Thanks a lot and I look forward to hearing from you.

Regards,
Eugene Gregorio

Author Jan 20, 2010
1:51 pm
#7 Ranadeep :

Thanks Eugene, you can use the contact form in this blog.

Jan 21, 2010
10:42 pm

Hi,

I found your blog on google and read a few of your other posts. I just added you to my Google News Reader. Keep up the great work Look forward to reading more from you in the future.

Jenni.

Author Feb 22, 2010
1:22 pm
#9 Ranadeep :

Wrong place to ask dude… :)

Trackbacks to this post.
Leave a Comment

Name

Email

Website

Previous Post
«
Next Post
CrossBlock designed by ZenVerse