Email contact form without refreshing page

Hello guys,

so I am dealing with this issue for quite some time now.
I need to write out a message on the site stating if the submitting of the contact form was succesfull or not (if some fields are not filled in for example). But I need to do it without the page refreshing. I tried different methods and tutorials, but none of them worked for me.

Here is the current code.


	<script type='text/javascript' src='../jquery.min.js'></script>
	<script type='text/javascript'>
	$(function(){
		$('input[type=submit]').click(function(){
			$.ajax({
				type: "POST",
				url: "post.php",
				data: $("#myform").serialize(),
							
				success: function(data){
					$('#result').html(data);
				}					
				});
			});
		})
	</script>
</head>
<body>
	<form action="" method="post" onsubmit="return false;" id="myform">
		Name: <input type='text' name='name' />
		Email: <input type='email' name='email' />
		Comments: <input type='text' name='comments' />
		<input type='submit' name='submit' value='Post'>
		<div id='result'></div>
		</form>

<?php

	if($_POST['submit']) {
	if(empty($_POST['name']) || empty($_POST['email']) || empty($_POST['comments'])) {
		echo "Error";
		
	} else {
	
		$to = "my mail";
		$name = trim($_POST['name']);
		$email = trim($_POST['email']);
		$comments = trim($_POST['comments']);
		
		$subject = "Contact Form";
		$headers = "From: $email";
		$messages = "Name: $name \\r\
 Email: $email \\r\
 Comments: $comments";
		$mailsent = mail($to, $subject, $messages, $headers);
		
		if($mailsent) {
			echo "Mail sent successfuly";
		}
	}
}
?>

I suppose this is a pretty common ‘feature’ on websites so I am sure many of you know how to do it.
Thanks a lot

Hi Randall,

The problem is with your first IF check in your php file:

if($_POST['submit']) { 

When the form is submitted via ajax there is no ‘submit’ value, and so the rest of the code never runs. A better way to check for a POST request is like this:

if ('POST' === $_SERVER['REQUEST_METHOD'])

Note that you probably want to return an error message if the sending of the email fails too.

There are also a couple of small changes you could make to improve your JS/HTML:


<body>
	<form method="post" id="myform">
		Name: <input type='text' name='name' />
		Email: <input type='email' name='email' />
		Comments: <input type='text' name='comments' />
		<input type='submit' name='submit' value='Post'>
		<div id='result'></div>
	</form>

	<script src="../jquery.min.js"></script>
	<script>
		$('#myform').submit(function(event) {
			event.preventDefault();
			$.ajax({
				type: "POST",
				url: "post.php",
				data: $(this).serialize(),		
				success: function(data){
					$('#result').html(data);
				}					
			});
		});
	</script>
</body>

By attaching the event handler to the forms submit event rather than the submit button’s click event, it’ll also work for users who press the enter key to submit the form. It’s also good practice not to put inline JS into your HTML, so you could remove the onSubmit attribute and prevent the form’s default action from within the handler function with event.preventDefault()

Thanks. I wish I knew php this well :slight_smile:

However it still doesn’t work. I fixed these two things, but it doesn’t send the mail or even writes out the message…

Could you re-post the contents of your post.php file please?

Sure. Here are both the main markup and post.php as they look now:

<html>
<head>

</head>
<body>
	<form method="post" id="myform">
		Name: <input type='text' name='name' />
		Email: <input type='email' name='email' />
		Comments: <input type='text' name='comments' />
		<input type='submit' name='submit' value='Post'>
		<div id='result'></div>
	</form>

	<script src="../jquery.min.js"></script>
	<script>
		$('#myform').submit(function(event) {
			event.preventDefault();
			$.ajax({
				type: "POST",
				url: "post.php",
				data: $(this).serialize(),		
				success: function(data){
					$('#result').html(data);
				}					
			});
		});
	</script>
</body>
</html>

<?php

	if ('POST' === $_SERVER['REQUEST_METHOD'])   {
	if(empty($_POST['name']) || empty($_POST['email']) || empty($_POST['comments'])) {
		echo "Error";
		
	} else {
	
		$to = "mymail";
		$name = trim($_POST['name']);
		$email = trim($_POST['email']);
		$comments = trim($_POST['comments']);
		
		$subject = "Contact Form";
		$headers = "From: $email";
		$messages = "Name: $name \\r\
 Email: $email \\r\
 Comments: $comments";
		$mailsent = mail($to, $subject, $messages, $headers);
		
		if($mailsent) {
			echo "Mail sent successfuly";
		}
	}
}
?>

Try adding in an extra check to see if there’s a problem actually sending the email:

if ('POST' === $_SERVER['REQUEST_METHOD'])
{
    if (empty($_POST['name']) || empty($_POST['email']) || empty($_POST['comments']))
    {
        echo "Error";
    }
    else
    {
        $to = "mymail";
        $name = trim($_POST['name']);
        $email = trim($_POST['email']);
        $comments = trim($_POST['comments']);

        $subject = "Contact Form";
        $headers = "From: $email";
        $messages = "Name: $name \\r\
 Email: $email \\r\
 Comments: $comments";
        $mailsent = mail($to, $subject, $messages, $headers);

        if ($mailsent)
        {
            echo "Mail sent successfuly";
        }
        else
        {
            echo "Error sending email";
        }
    }
}

Aaah, so the problem was elsewhere. I was using WAMP server. Then I tried uploading it on my site and now it works! Thank you fretburner :wink: