Link to home
Start Free TrialLog in
Avatar of garrett jones
garrett jones

asked on

Contact form not sending message

Hello, first off i am a novice here. I am a designer but no coding knowledge. My problem is  i'm trying to get this contact form to send messages but it's only letting the user input text into the fields but when you hit the send button nothing is sent. Any help is much appreciated.

the php action is attached.
the form code:

 	<script type="text/javascript">
			$(function(){
				/* ========================================================================= */
				/*	Contact Form
				/* ========================================================================= */
				
				$('#contact-form').validate({
					rules: {
						name: {
							required: true,
							minlength: 2
						},
						email: {
							required: true,
							email: true
						},
						message: {
							required: true
						}
					},
					messages: {
						name: {
							required: "come on, you have a name don't you?",
							minlength: "your name must consist of at least 2 characters"
						},
						email: {
							required: "no email, no message"
						},
						message: {
							required: "um...yea, you have to write something to send this form.",
							minlength: "thats all? really?"
						}
					},
					submitHandler: function(form) {
						$(form).ajaxSubmit({
							type:"POST",
							data: $(form).serialize(),
							url:"gdform.php",
							success: function() {
								$('#contact-form :input').attr('enabled', 'enabled');
								$('#contact-form').fadeTo( "slow", 0.15, function() {
									$(this).find(':input').attr('enabled', 'enabled');
									$(this).find('label').css('cursor','default');
									$('#success').fadeIn();
								});
							},
							error: function() {
								$('#contact-form').fadeTo( "slow", 0.15, function() {
									$('#error').fadeIn();
								});
							}
						});
					}
				});
			});
		</script>

Open in new window

Avatar of Chris Stanyon
Chris Stanyon
Flag of United Kingdom of Great Britain and Northern Ireland image

Hey Garrett. Welcome to EE.

First off - a quick tip - it makes it much easier for us to read your question if you enclose any code in the CODE tags (you'll see the code button on the toolbar when you post a comment). I've edited your question :)

Now, onto your code. It looks like you've lifted your example straight off the Validate website. The example uses a 3rd party plugin called jQuery Form, which gives you the ajaxSubmit() function. It's not part of the core jQuery library, so unless you've explicitly included that library, you can't use the ajaxSubmit function.

When you're coding and debugging like this, it always pays to have your browser's console open. You can access it by pressing F12 within your browser. That will show you any errors and is likely to show that ajaxSubmit is not a function.

You can either include the 3rd party library, or you can use the native jQuery AJAX function. For the latter, just change line 35 of the above code to the following:

$.ajax({

You will end up with:

submitHandler: function(form) {
    $.ajax({
        type:"POST",
        data: $(form).serialize(),

Open in new window

FYI - You didn't attach any PHP handler scripts!
Avatar of garrett jones
garrett jones

ASKER

Hey Chris, Thanks for all the help. I made the  change with  from: $(form).ajaxSubmit({ to  $.ajaxSubmit({ on line 35 but now after hitting send it ends up on a blank page. is it possible to return the visitor to where they left off? If so, how do i do that? i'm reattaching the PHP handler script again.
gdform.php
Hey Garrett,

The code change suggested was to $.ajax, not $.ajaxSubmit:

submitHandler: function(form) {
    $.ajax({

Looking at your Mailer script, there's a couple of points I would make.

1. While technically not wrong, using curly brackets for arrays is very unconventional. I don't think I've ever actually seen it used. The accepted norm is to use square brackets: $fields['name']

2. Again, nothing technically wrong, but I would always suggest you explicitly choose $_GET or $_POST over $_REQUEST - personally I think it makes it more obvious in your code what you expect (POST for form data / GET for Querystring). By using $_REQUEST you could end up inadvertently processing a query string instead of a form.

3. That's an interesting take on the variable assignment and loop. Any reason why you don't just loop through POST data directly: foreach ($_POST as $key => value)

4. You're not actually doing anything at the end of your script, so your user will get no feedback about what happened. When they click on the submit button, your script will be called, your form will fade ... and that will be the end of it. You might want to look at offering some feedback.

One final point which is more of a suggestion. The built in mail() function from php is not overly reliable or flexible. You may want to look at a library called PHPMailer
Hey Chris,
 I did totally drop the ball on the first change but i corrected my mistake and now it's functioning correctly again but still not sending me the form messages to my gmail account that i have in the PHP script.   I guess it might be go daddy's basic hosting that's not allowing the messages to be sent. I will have to try and figure that out. I do have one last question. If i want to simply have the form to say "message sent" after its sent how would i add that function?
Hey Garrett,

Good news.

Like I said previously, the php mail() function is unrealiable at best. It relies on the internal configuration to send emails, so you have no way of authenticating yourself, or really specifying any of the options needed to correctly send email. I would strongly recommend that you don't use it. Switch to PHPMailer - it will give you full control over your email.

Now for the response. When you make an AJAX request to a server-side script, whatever that script outputs is returned to your AJAX call as an argument of the success handler (or error handler if something went wrong). You can write your script to return (output) whatever you like (simple text / HTML / JSON etc.).

For example:

<?php
if ( $mail->send() ):
    echo "Your mail was sent successfully";
else:
    echo "There was a problem sending your email";
endif;

Open in new window

The script is outputting a simple string, which is passed back to your AJAX call as the argument of the success handler:

type:"POST",
data: $(form).serialize(),
url:"gdform.php",
success: function(data) {
    alert(data);
    ...

Open in new window

You'll see the success handler takes a argument (called data in my example, but you can call it whatever you like). If then just alerts that data to the user. You can do whatever you like with the data, such as alert it or inject it into your HTML:

$('#someElement').html( data );
Chris,
Good Morning. I actually got the form working now thanks to you. As far as getting the response to work no luck yet.  I'm not clear about your instructions. This is what i did here:
                                             type:"POST",
							data: $(form).serialize(),
							url:"gdform.php",
							success: function(data) {
							alert(data);

Open in new window


<?php

    $to = "admin@myemail.com";
    $from = $_POST['name'];
    $subject = $_POST['subject'];
    $name = $_POST['name'];
    $headers = "From: $from";

    $fields = array();
    $fields{"name"} = "name";
    $fields{"email"} = "email";
    $fields{"subject"} = "subject";
    $fields{"message"} = "message";

    $body = "Here is what was sent:\n\n"; foreach($fields as $a => $b){   $body .= sprintf("%20s: %s\n",$b,$_REQUEST[$a]); }

    $send = mail($to, $subject, $body, $headers);
	
    if ( $mail->send() ):
    echo "Your mail was sent successfully";
    else:
    echo "There was a problem sending your email";
    endif;
?>

Open in new window


and and far as this:  $('#someElement').html( data ); not sure where to place this.
Hey Garrett,

Right. My code was just a simple example. In your code, the mail() function will return true or false, depending on whether the mail was sent correctly, and you're assigning the results of that call to a variable called $send (so $send will be either true or false). You would need something like this in your script:

...
$send = mail($to, $subject, $body, $headers);
	
if ( $send ):
    echo "Your mail was sent successfully";
else:
    echo "There was a problem sending your email";
endif;

Open in new window

Because that string is sent back to your AJAX handler, you can use it:

success: function(data) {
    alert(data);
    $('#someElement').html( data );
    ...

Open in new window

The second part of that will look for an element in your HTML page with an ID of someElement, and put the text from your server-side script into it, so in your HTML page, you might have something like this:

<div id="someElement"></div>

And when your AJAX call has finished, whatever was returned to it will be dropped into that element.
Chris,
Thanks for all of your help. I finally got it all working now. You're the best my friend.
ASKER CERTIFIED SOLUTION
Avatar of Chris Stanyon
Chris Stanyon
Flag of United Kingdom of Great Britain and Northern Ireland image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial