Send PHP email using jQuery AJAX

I am stuck with my portfolio PHP email.

There is a div containing email form. This div fades in (initially display: none; and than jQuery opens it) when the button “contact” is clicked. Validation for this form is done in PHP, so if all required data is typed in, PHP displays the sentence “Thank you for your email…”(instead of previously displayed form) and if all required data is not typed in, than the error message(s) is/are displayed beside the corresponding input tag(s).

The problem is that after clicking the submit email button, the popup which contains email form disappears and user cannot see the feedback (feedback will be there if user reopens the popup, but I doubt anyone would try to reopen the popup after it disappears - not intuitive).

I am trying to make that popup remain displayed with updated content (“Thank you for your email…” or eventual error messages), and I believe I should do that with jQuery AJAX but I do something wrong. Could anyone help me out with this please?

home.php:

<?php
include 'includes/email.php';
?>
<!DOCTYPE html>
<html lang="en">
	<head>
		<title>myPortfolio</title>	
		<script>
			$('#btnSend').click(function(){
					
						$.ajax({
						url : 'includes/thirdPopup.php',
						type: 'post',
						data: $('#formContent').serialize().done( function( ){  });
				});	
			});		
		</script>
		<?php
			include 'includes/style.php';
			include 'includes/script.php';
		?>
	</head>
	<body>
		<div id="master">			
			<?php
				include 'includes/portfolioHeader.php';
				include 'includes/portfolioNavigation.php';
				include 'includes/firstPopup.php';
				include 'includes/secondPopup.php';
				include 'includes/thirdPopup.php';
				include 'includes/portfolioContent.php';
				include 'includes/portfolioFooter.php';
			?>
		</div>
	</body>
</html>

thirdPopup.php (include file containing email form):

<?php
//thirdPopup.php
?>
<div id="popup3">
	<input type="image"  id="closePopup3" value="Send" src="img/close.png" onMouseOver="this.src='img/closeOver.png'" onMouseOut="this.src='img/close.png'" />
	<h1 class="popupHeading">Contact</h1>
	<div id="formContent">
		<?php
			if ($posted == false){
		?>
		<form name="contactForm" id="contactForm" action="<?=$_SERVER['PHP_SELF']?>" method="post">
			<fieldset>
				<table id="tableName">
					<tr>
						<td colspan="2">Name:</td>
					</tr>
					<tr>
						<td id="nameInput">
							<input type="text" name="name" id="name" value="<?=htmlspecialchars($name);?>" />
						</td>
						<td>
							<?php
								if(isset($errMsg1) && !empty($errMsg1)){
									echo '<p id="error1">' . $errMsg1 . '</p>';	
								}
							?>
						</td>
					</tr>
				</table>
				<table id="tableEmail">
					<tr>
						<td colspan="2">Email:</td>
					</tr>
					<tr>
						<td id="emailInput">
							<input type="text" name="email" id="email" value="<?=htmlspecialchars($email);?>" />
						</td>
						<td>
							<?php
								if(isset($errMsg2) && !empty($errMsg2)){
									echo '<p id="error2">' . $errMsg2 . '</p>';	
								}
								if(isset($errMsg3) && !empty($errMsg3)){
									echo '<p id="error3">' . $errMsg3 . '</p>';	
								}
							?>
						</td>
					</tr>
				</table>
				<table id="tableSubject">
					<tr>
						<td id="subjectLabel">Subject:</td>
						<td>
							<?php
								if(isset($errMsg5) && !empty($errMsg5)){
									echo '<p id="error5">(' . $errMsg5 . ')</p>';	
								}
							?>
						</td>
					</tr>
					<tr>
						<td  colspan="2">
							<input type="text" name="subject" id="subject" value="<?=htmlspecialchars($subject);?>" />
						</td>
					</tr>
				</table>	
				<table id="tableMessage">
					<tr>
						<td id="messageLabel">Message:</td>
						<td>
							<?php
								if(isset($errMsg6) && !empty($errMsg6)){
									echo '<p id="error6">(' . $errMsg6 . ')</p>';	
								}
							?>
						</td>
					</tr>
					<tr>
						<td  colspan="2">
							<textarea name="message" id="message" rows="7"><?=htmlspecialchars($msg);?></textarea>
						</td>
					</tr>
				</table>							
				<table id="tableCaptcha">
					<tr>
						<td id="captchaLabel">Captcha Code:</td>
						<td rowspan="2">
							<img src="CaptchaSecurityImages.php?width=100&height=40&characters=5" id="captchaImg" />		
						</td>
					</tr>
					<tr>
						<td>
							<input type="text" id="security_code" name="security_code" value="<?=htmlspecialchars($code);?>" />						
						</td>
					</tr>
				</table>
				
				
				<table  id="tableSubmit">
					<tr>
						<td>
							<input type="image" name="btnSend" id="btnSend" value="Send" width="106" height="59" src="img/send.png" onMouseOver="this.src='img/sendOver.png'" onMouseOut="this.src='img/send.png'" onmousedown="emailSubmitted()" />
						</td>
						<td>
							<?php
								if(isset($errMsg4) && !empty($errMsg4)){
									echo '<p id="error4">' . $errMsg4 . '</p>';	
								}
							?>
						</td>
					</tr>
				</table>
				
			</fieldset>
		</form>
		<?php } ?>
		<?php
			if(isset($feedback) && !empty($feedback)){
				echo '<p class="info">' . $feedback . '</p>';
			}
		?>		
	</div>	
</div>

email.php (include file that validates and sends the email):

<?php
session_start();

$name = "";
$email = "";
$code = "";
$subject = "";
$msg = "";
$valid = true;
$posted = false;
$errMsg1 = "";
$errMsg2 = "";
$errMsg3 = "";
$errMsg4 = "";
$errMsg5 = "";
$errMsg6 = "";

if(isset($_POST['email'])){
	$name = strip_tags(trim($_POST['name']));
	$email = strip_tags(trim($_POST['email']));
	$subject = strip_tags(trim($_POST['subject']));
	$msg = strip_tags(trim($_POST['message']));
	$code = strip_tags(trim($_POST['security_code']));	
	
	
	/************************************
	PREVENTING HEADERS INSERTION
	*************************************/		
	
	if( eregi("(multipart\\alternative|content-type:|cc:|bcc:|boundary=)", $name )){
		die('Sorry but my email server does not like you.');	
	}else if( eregi("(multipart\\alternative|content-type:|cc:|bcc:|boundary=)", $email )){
		die('Sorry but my email server does not like you.');	
	}else if( eregi("(multipart\\alternative|content-type:|cc:|bcc:|boundary=)", $subject )){
		die('Sorry but my email server does not like you.');	
	}else if( eregi("(multipart\\alternative|content-type:|cc:|bcc:|boundary=)", $msg )){
		die('Sorry but my email server does not like you.');	
	}
	
	
	/***************************************************
	PREVENTING INVALID EMAIL AND BLANK FIELDS
	****************************************************/	
	function is_valid_email($email) {
		$result = true;
		if((!eregi("^[_a-z0-9-]+(\\.[_a-z0-9-]+)*@[a-z0-9-]+(\\.[a-z0-9-]+)*(\\.[a-z]{2,4})$", $email)) && ( !empty($email))) {
			$result = false;
		}
		return $result;
	}
	function is_valid_code($code) {
		$result = false;
		if( $_SESSION['security_code'] == $_POST['security_code'] && !empty($_SESSION['security_code'] ) ) {
			// Insert you code for processing the form here, e.g emailing the submission, entering it into a database.
			//echo 'Thank you. Your message said "'.$_POST['message'].'"';
			unset($_SESSION['security_code']);
			$result = true;
	    } else {
			// Insert your code for showing an error message here
			//echo 'Sorry, you have provided an invalid security code';
			$result = false;
	    }
		return $result;
	}
	if( empty($name)){
	    $valid = false;
	    $errMsg1 = "Your name?";
	}	
	if( empty($email)){
	    $valid = false;
	    $errMsg2 = "Your email?";
	}	
	if (!is_valid_email($email) && !empty($email)){
		$valid = false;
		$errMsg3 = "Invalid email.";
	}
	if (!is_valid_code($code)){
		$valid = false;
		$errMsg4 = "Please retype the captcha code and help me avoid getting email spam. Thanks.";
	}
	if( empty($subject)){
	    $valid = false;
	    $errMsg5 = "Please type in your subject.";
	}
	if( empty($msg)){
	    $valid = false;
	    $errMsg6 = "Please type in your message.";
	}
	
	if($valid){
	    //send the email	
			$headers = "From: $name <$email> \
";
			$headers .= "Reply-To: $name <$email>";			
			$subject = trim($_POST['subject']);		
			$msg = trim($_POST['message']);
			$sendTheMail = mail('myname@mail.com', $subject, $msg, $headers);
			$feedback = '<p id="emailSent">The email was successfully sent. <span>Thank you.</span></p>';
			$posted = true;
	}else{
	    //do not send the email	
	}
}
?>

The reason your not seeing any feedback is because your PHP script isn’t echoing anything to the response, also you currently don’t have anything setup for your ajax request to handle the response which you have you have to code yourself within the success state of the request as jQuery can’t handle this for you.

On another note your current code has a syntax error in it.

$.ajax({
    url : 'includes/thirdPopup.php', 
    type: 'post', 
    data: $('#formContent').serialize()[B][COLOR=#ff0000].done( function( ){  }); [/COLOR][/B]
});

I assume you are attempting you use promises which requires you initiate a promise() call before done() can be used.

$.ajax({
    url : 'includes/thirdPopup.php', 
    type: 'post', 
    data: $('#formContent').serialize() 
})
.promise()
.done(function(data) {
    alert(data);
});

Thank you.