Jump to content

One page website contact form with jquery validation?


photoman355
 Share

Recommended Posts

I am in the process of converting over a one page website to work with PW and am at the stage of hooking up the contact form but it's not working.  I'm using the phpMailer script with a bit of jquery to process the form validation.  

I'm not set on converting over my current form to work with PW as the phpMailer script is a bit out of date now.  All I need is something that works, outputs validation without a page refresh and ideally has some anti-spam measures built in.  I know Ryan built the Form Template Processor so wasn't sure if this is a better route to go down?

Here's the jquery for my current form.

$(function() {
    // These first three lines of code compensate for Javascript being turned on and off. 
    // It simply changes the submit input field from a type of "submit" to a type of "button".

    var paraTag = $('input#submit').parent('p');
    $(paraTag).children('input').remove();
    $(paraTag).append('<input type="button" name="submit" id="submit" class="btn pull-right"    value="Send" />');

    $('#main input#submit').click(function() {
        $('#main').append('<img src="assets/img/mail-ajax-loader2.gif" class="loaderIcon" alt="Loading..." />');

        var name = $('input#form_name').val();
        var email = $('input#form_email').val();
		var subject = $('input#form_subject').val();
        var comments = $('textarea#form_message').val();

        $.ajax({
            type: 'post',
			url: 'sendEmail.php',
            data: 'name=' + name + '&email=' + email + '&subject=' + subject + '&comments=' + comments,

            success: function(results) {
                $('#main img.loaderIcon').fadeOut(1000);
                $('ul#response').html(results);
            }
        }); // end ajax
    });
});
		 

Any advice is greatly appreciated.

Link to comment
Share on other sites

Here use this:

<?php

$sent = false;
$error = '';
$emailTo = 'YOUR EMAIL ADDRESS'; // or pull from PW page field

// sanitize form values or create empty
$form = array(
    'fullname' => $sanitizer->text($input->post->fullname),
    'email' => $sanitizer->email($input->post->email),
    'comments' => $sanitizer->textarea($input->post->comments),
    ); 

// check if the form was submitted
if($input->post->submit) {
        
    // determine if any fields were ommitted or didn't validate
    foreach($form as $key => $value) {
        if(empty($value)) $error = "<p class='error'>Please check that you have completed all fields.</p>";
    }

    // if no errors, email the form results
    if(!$error) {
        $msg = "Full name: $form[fullname]\n" . 
               "Email: $form[email]\n" . 
               "Comments: $form[comments]"; 

        mail($emailTo, "Website contact form submission", "$form[comments]", "From: $form[email]");

        // populate body with success message, or pull it from another PW field
        $page->body = "<div id='message-success'><p>Thanks, your message has been sent.</p></div>"; 
        $sent = true;   
    }
}

if(!$sent) {

    // sanitize values for placement in markup
    foreach($form as $key => $value) {
        $form[$key] = htmlentities($value, ENT_QUOTES, "UTF-8"); 
    }

    // append form to body copy
    $page->body .= <<< _OUT
    	$error
        <form action="./" method="post" id="contact-form">
			<fieldset>
				<legend>Send a note</legend>
					<ol>
						<li class="form-row">
							<span class="error" style="display: none;" ></span>
						</li>
						<li class="form-row">
							<input id="fullname" name="fullname" type="text" size="30" class="name required default" title="Your name" value="$form[fullname]"/>
						</li>
						<li class="form-row">
							<input id="inputemail" name="email" type="text" size="30" class="required email default" title="Your email address" value="$form[email]" />
						</li>
						<li class="form-row">
							<textarea name='comments' rows='5' cols='45' id='comments' title="Your message">$form[comments]</textarea>
						</li>
						<li class="form-row">
							<input type="submit" name="submit" value="Send" class="submit-button"/>
						</li>
					</ol>
			</fieldset>
        </form>

_OUT;

}
?><?php 

/**
 * Contact form template
 *
 */

include("./header.inc"); 
?>
        <div class="main-container">
            <div class="main wrapper clearfix">
                <article>
                    <section>
	                    <?php echo $page->body; ?>
                    </section>
                </article>
            </div> <!-- #main -->
        </div> <!-- #main-container -->
<?
include("./footer.inc"); 


Oops and here is the jquery for validation:

$(document).ready(function() {
	$(".default").each(function(){
		var defaultVal = $(this).attr('title');
		$(this).focus(function(){
			if ($(this).val() == defaultVal){
				$(this).removeClass('active').val('');
			}
		});
		$(this).blur(function() {
			if ($(this).val() == ''){
				$(this).addClass('active').val(defaultVal);
			}
		})
		.blur().addClass('active');
	});
	$('.submit-button').click(function(e){
		var $formId = $(this).parents('form');
		var formAction = $formId.attr('action');
		defaulttextRemove();
		var emailReg = /^([\w-\.]+@([\w-]+\.)+[\w-]{2,4})?$/;
		$('li',$formId).removeClass('contact-form-error');
		$('span.contact-form-error').remove();
		$('.required',$formId).each(function(){
			var inputVal = $(this).val();
			var $parentTag = $(this).parent();
			if(inputVal == ''){
				$parentTag.addClass('contact-form-error').append('<span class="contact-form-error">Required field</span>');
			}
			if($(this).hasClass('email') == true){
				if(!emailReg.test(inputVal)){
					$parentTag.addClass('contact-form-error').append('<span class="contact-form-error">Enter a valid email address.</span>');
				}
			}
		});
		if ($('span.contact-form-error').length == "0") {
			$formId.append($loading.clone());
			$('fieldset',$formId).hide();
			$.post(formAction, $formId.serialize(),function(data){
				$('.loading').remove();
               $formId.append(data).fadeIn();
        	});
		}
		e.preventDefault();
	});

function defaulttextRemove(){
	$('.default').each(function(){
		var defaultVal = $(this).attr('title');
		if ($(this).val() == defaultVal){
			$(this).val('');
		}
	});
}
});
  • Like 3
Link to comment
Share on other sites

url: 'sendEmail.php',

Double check that you don't need a more specific URL for this. I'm guessing you might need it to be "/sendEmail.php" instead?

data: 'name=' + name + '&email=' + email + '&subject=' + subject + '&comments=' + comments,

I would guess those values have to be escaped if you bundle them in a string like that. To make it simpler, I would suggest changing this to:

data: {
  name: name,
  email: email,
  subject: subject,
  comments: comments
}
  • Like 1
Link to comment
Share on other sites

Thanks guys.  I have both forms working now but I'm still struggling to get the form to submit and post results without a page refresh.  As this is for a one page website a page refresh looks pretty bad.  On my original form I have ajax doing that for me.  

Here's a rough idea of the page structure.

Home --  (header.inc & footer.inc)

    Page 1  --  (Pulled into home)

         Contact  --  (Pulled into Page)

   Page 2 (etc)

The only way I can get the forms to work at the moment is by putting the php inside a page template and assigning that to "Contact".  This is the way Andrew's form works but my original form called the php file separately for processing only.  Is the former the correct way to implement forms in PW?

Is there something special I have to do to get the ajax working or is there an alternative non ajax way of rendering results without a page refresh? 

Link to comment
Share on other sites

I have a little more info after playing around with the setup.  I am referencing the mail script like this:
 
<form action='<?=$config->urls->templates?>sendEmail.php' method='post'>

This is definitely the correct URL to the script, I can see it in firebug however I'm getting a 404 redirect when submitting the form.  I tried disabling javascript (The form also works without it) but I still get a 404.  

This would suggest to me that it's possible something in PW is stopping the script from running.  Any ideas?

Link to comment
Share on other sites

Aha! Should have thought of that.  It's working now, many thanks Soma.  

I'm guessing it's not good practice to put php files in the root especially for exporting sites?  Is there a better way to handle ajax loading for the above setup in PW?

I have another quick question about referencing PW urls via jquery.  At the moment I have to reference the full URL including http etc.  Is there a way to point to the root of my PW installation by using variables?  Something that effectively does this:

var root = '<?=$config->urls->root?>';

So that any subsequent url in jquery can be eg 'site/templates/assets/img/myimage.jpg'.  I mainly want to do this to remove the need to rewrite the JS every time I install a site profile.

Link to comment
Share on other sites

You can also boostrap. I often put an ajax folder in root and have check in the php if processwire is defined. So it cant be called directly.

Yes you nailed it. Your example to use root var in your scripts.

Link to comment
Share on other sites

  • 8 months later...

Hey @all.

I'd like to dig out this old thread cause always I'm working on singlepagers this topic comes up and still not sure what is the best practise with this. Especially I'd like to ask about the part with the sendMail.php on root-level. As photoman355 stated I understand that php-files shouldn't lay on root-level.

I'm guessing it's not good practice to put php files in the root especially for exporting sites?  Is there a better way to handle ajax loading for the above setup in PW?

But I do not get Somas answer. Could anybody please explain that a little further..

You can also boostrap. I often put an ajax folder in root and have check in the php if processwire is defined. So it cant be called directly.

Or is there any other approach to handle form-submissions via ajax?

Thanks in advance!

Sry again for the two prior edits ..

Link to comment
Share on other sites

Hey @all.

 Or is there any other approach to handle form-submissions via ajax?

Thanks in advance!

Make a page and a template. Put the ajax handling code in the template file and post the data to the page's URL. You can use page fields to store settings if you need any or your code.
  • Like 1
Link to comment
Share on other sites

  • 2 months later...

If I make a page template as SteveB suggested, a construct like the below for getting the form with javascipt, will work?

contact_form.submit(function() {
$.post( "../site/templates/contact.php" );
});

I just want to show the validation that happens on contact.php in the current page.

Link to comment
Share on other sites

  • 7 months later...

Hi,

my first post here in this forum is a question about the jQuery-Validation script at the beginning of this page.

The form above the jQuery-Code is running well... But now i want to validate it and don´t know how...

Do i have to put the jQuery-Code in a file and include it to the contact.php (template) or how does it works?

What is to do with it?

Thanks

nukleuz

Link to comment
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
 Share

×
×
  • Create New...