Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Mike Lewis on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Help with info request form - not getting generated email

Status
Not open for further replies.

Evil8

MIS
Mar 3, 2006
313
US
Code for info.php
Code:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "[URL unfurl="true"]http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">[/URL]
<html xmlns="[URL unfurl="true"]http://www.w3.org/1999/xhtml">[/URL]
<head>
<title>Create a Ajax based form submission with jQuery</title>

<script type="text/javascript" src="[URL unfurl="true"]http://code.jquery.com/jquery-latest.js"></script>[/URL]
<script type="text/javascript">
$(document).ready(function() {
	
	//if submit button is clicked
	$('#submit').click(function () {		
		
		//Get the data from all the fields
		var name    = $('input[name=name]');
		var phone   = $('input[name=phone]');
		var email   = $('input[name=email]');
		var age     = $('input[name=age]');
		var gender  = $('input[name=gender]');
		var state   = $('input[name=state]');
		var comment = $('textarea[name=comment]');

		//Simple validation to make sure user entered something
		//If error found, add hightlight class to the text field
		if (name.val()=='') {
			name.addClass('hightlight');
			return false;
		} else name.removeClass('hightlight');
		
		if (phone.val()=='') {
			phone.addClass('hightlight');
			return false;
		} else phone.removeClass('hightlight');
		
		if (email.val()=='') {
			email.addClass('hightlight');
			return false;
		} else email.removeClass('hightlight');
		
		if (age.val()=='') {
			age.addClass('hightlight');
			return false;
		} else age.removeClass('hightlight');
		
		if (gender.val()=='') {
			gender.addClass('hightlight');
			return false;
		} else gender.removeClass('hightlight');
		
		if (state.val()=='') {
			state.addClass('hightlight');
			return false;
		} else state.removeClass('hightlight');
		
		if (comment.val()=='') {
			comment.addClass('hightlight');
			return false;
		} else comment.removeClass('hightlight');
		
		//organize the data properly
		var data = 'name=' + name.val() + '&phone=' + phone.val() + '&email=' + email.val() + '&age=' + 
		age.val() + '&gender=' + gender.val() +'&state=' + state.val() + '&comment='  + encodeURIComponent(comment.val());
		
		//disabled all the text fields
		$('.text').attr('disabled','true');
		
		//show the loading sign
		$('.loading').show();
		
		//start the ajax
		$.ajax({
			//this is the php file that processes the data and send mail
			url: "process.php",	
			
			//GET method is used
			type: "GET",

			//pass the data			
			data: data,		
			
			//Do not cache the page
			cache: false,
			
			//success
			success: function (html) {				
				//if process.php returned 1/true (send mail success)
				if (html==1) {					
					//hide the form
					$('.form').fadeOut('slow');					
					
					//show the success message
					$('.done').fadeIn('slow');
					
				//if process.php returned 0/false (send mail failed)
				} else alert('Sorry, unexpected error. Please try again later.');				
			}		
		});
		
		//cancel the submit button default behaviours
		return false;
	});	
});	
</script>
<style>
body{text-align:center;}
.clear {
	clear:both
}
.block {
	width:400px;
	margin:0 auto;
	text-align:left;
}
.element * {
	padding:5px; 
	margin:2px; 
	font-family:arial;
	font-size:12px;
}
.element label {
	float:left; 
	width:75px;
	font-weight:700
}
.element input.text {
	float:left; 
	width:270px;
	padding-left:20px;
}
.element .textarea {
	height:120px; 
	width:270px;
	padding-left:20px;
}
.element .hightlight {
	border:2px solid #9F1319;
	background:url(images/iconCaution.gif) no-repeat 2px
}
.element #submit {
	float:right;
	margin-right:10px;
}
.loading {
	float:right; 
	background:url(images/ajax-loader.gif) no-repeat 1px; 
	height:28px; 
	width:28px; 
	display:none;
}
.done {
	background:url(images/iconIdea.gif) no-repeat 2px; 
	padding-left:20px;
	font-family:arial;
	font-size:12px; 
	width:70%; 
	margin:20px auto; 
	display:none
}
</style>
<body>


<div class="block">
<div class="done">
<b>Thank you !</b> We have received your message. 
</div>
	<div class="form">
	<form method="post" action="process.php">
	<div class="element">
		<label>Name</label>
		<input type="text" name="name" class="text" />
	</div>
	<div class="element">
		<label>Phone</label>
		<input type="text" name="phone" class="text" />
	</div>
	<div class="element">
		<label>Email</label>
		<input type="text" name="email" class="text" />
	</div>
	<div class="element">
		<label>Age</label>
		<input type="text" name="age" class="text" />
	</div>
	<div class="element">
		<label>Gender</label>
		<input type="text" name="gender" class="text" />
	</div>
	<div class="element">
		<label>State of Residence</label>
		<input type="text" name="state" class="text" />
	</div>
	<div class="element">
		<label>Comment</label>
		<textarea name="comment" class="text textarea" /></textarea>
	</div>
	<div class="element">
		
		<input type="submit" id="submit"/>
		<div class="loading"></div>
	</div>
	</form>
	</div>
</div>

<div class="clear"></div>



</body>
</html>
Validation works if inputs are empty. Returns successful if all boxes are filled but I don't get the generated email. Here's the code for process.php:
Code:
<?php

//Retrieve form data. 
//GET - user submitted data using AJAX
//POST - in case user does not support javascript, we'll use POST instead
$name = ($_GET['name']) ?$_GET['name'] : $_POST['name'];
$phone = ($_GET['phone']) ?$_GET['phone'] : $_POST['phone'];
$email = ($_GET['email']) ?$_GET['email'] : $_POST['email'];
$age = ($_GET['age']) ?$_GET['age'] : $_POST['age'];
$gender = ($_GET['gender']) ?$_GET['gender'] : $_POST['gender'];
$state = ($_GET['state']) ?$_GET['state'] : $_POST['state'];
$comment = ($_GET['comment']) ?$_GET['comment'] : $_POST['comment'];

//flag to indicate which method it uses. If POST set it to 1
if ($_POST) $post=1;

//Simple server side validation for POST data
if (!$name) $errors[count($errors)] = 'Please enter your name.';
if (!$phone) $errors[count($errors)] = 'Please enter your contact phone.';
if (!$email) $errors[count($errors)] = 'Please enter your contact email.';
if (!$age) $errors[count($errors)] = 'Please enter your age.';
if (!$gender) $errors[count($errors)] = 'Please enter your gender.';
if (!$state) $errors[count($errors)] = 'Please enter your state of residence.';
if (!$comment) $errors[count($errors)] = 'Please enter your comment or request.'; 

//if the errors array is empty, send the mail
if (!$errors) {

	//recipient
	$to = 'Evil8 <evil8@mymail.com>';	
	//sender
	$from = $name . ' <' . $email . '>';
	
	//subject and the html message
	$subject = 'Comment from ' . $name;	
	$message = '
	<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" 
	"[URL unfurl="true"]http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">[/URL]
	<html xmlns="[URL unfurl="true"]http://www.w3.org/1999/xhtml">[/URL]
	<head></head>
	<body>
	<table>
		<tr><td>Name</td><td>' . $name . '</td></tr>
		<tr><td>Phone</td><td>' . $phone . '</td></tr>
		<tr><td>Email</td><td>' . $email . '</td></tr>
		<tr><td>Age</td><td>' . $age . '</td></tr>
		<tr><td>Gender</td><td>' . $gender . '</td></tr>
		<tr><td>State</td><td>' . $state . '</td></tr>
		<tr><td>Comment</td><td>' . nl2br($comment) . '</td></tr>
	</table>
	</body>
	</html>';

	//send the mail
	$result = sendmail($to, $subject, $message, $from);
	
	//if POST was used, display the message straight away
	if ($_POST) {
		if ($result) echo 'Thank you! We have received your message.';
		else echo 'Sorry, unexpected error. Please try again later';
		
	//else if GET was used, return the boolean value so that 
	//ajax script can react accordingly
	//1 means success, 0 means failed
	} else {
		echo $result;	
	}

//if the errors array has values
} else {
	//display the errors message
	for ($i=0; $i<count($errors); $i++) echo $errors[$i] . '<br/>';
	echo '<a href="info.php">Back</a>';
	exit;
}


//Simple mail function with HTML header
function sendmail($to, $subject, $message, $from) {
	$headers = "MIME-Version: 1.0" . "\r\n";
	$headers .= "Content-type:text/html;charset=iso-8859-1" . "\r\n";
	$headers .= 'From: ' . $from . "\r\n";
	
	$result = mail($to,$subject,$message,$headers);
	
	if ($result) return 1;
	else return 0;
}

?>

Thanks for any help.
 
I think I might have to set up something (smtp?) on the web server (I'm using inmotionhosting) and refer to that in my code to actually get the email to work. Please let me know if I'm wrong or there is a secure way around that. Thanks!
 
So what are you getting from the mail function. As documented in the code 1 means success 0 means failure. If you are getting a 1, then mail is successfully handing the email off to the mail server. At which point it stops being a PHP matter and becomes a mailing problem.

If you are getting a 0 then the mail() function can't find your mail server to hand off the email to. In which case you'd need to check the configuration of your mail sever, and the php.ini in the relevant sections for it.

If your server is a Linux box the mail server is built in, if its Windows then you'd need to install one, or maybe use your ISP's mail server instead.



----------------------------------
Phil AKA Vacunita
----------------------------------
Ignorance is not necessarily Bliss, case in point:
Unknown has caused an Unknown Error on Unknown and must be shutdown to prevent damage to Unknown.

Web & Tech
 
I am getting 1 or success, but no email. Doing more research I think it is a mail/server issue. I don't do this everyday, so I wanted to make sure I was coding properly. I'm using inmotionhosting to host the website and I've contacted their customer service on that issue.
 
Since it is getting passed on, make sure the email is not ending up in your Spam folder. Other than that lets see what your host has to say about it.

----------------------------------
Phil AKA Vacunita
----------------------------------
Ignorance is not necessarily Bliss, case in point:
Unknown has caused an Unknown Error on Unknown and must be shutdown to prevent damage to Unknown.

Web & Tech
 
1. check and see if you can send a email from a simple 1 line script
such as
Code:
$result = mail('evil8@mymail.com', 'hi', 'test', 'someone@somewhere.com');

if ($result){
   echo "1";
else{
   echo "0";
}

if the msg sends then work backwards adding pieces and testing. Continue until you have it all working. My old php doesn't like your $message construction so it might end up being something along that vein.
 
My webhost customer support insists I need to set up an email address within the framework of our account and server connection/login to my code for this to work. I'll work on it this week.
 
i can't see why the insist. email is just a socket connection out of the server. however receiving machines sometimes do DNS checks to make sure that the sender IP address is within the domain of the sender email.

you could also use gmail to do your sending (attach to them via smtp as normal - see phpmailer for a class that will do this). gmail has a 'send as' feature that works fine.
 
I added this code to my process.php from examples I found elsewhere.

Code:
require_once('phpmailer/class.phpmailer.php');

	$mail = new PHPMailer();  // create a new object
	$mail->IsSMTP(); // enable SMTP
	$mail->SMTPDebug = 2;  // debugging: 1 = errors and messages, 2 = messages only
	$mail->SMTPAuth = true;  // authentication enabled
	$mail->SMTPSecure = 'ssl'; // secure transfer enabled REQUIRED for GMail
	$mail->Host = 'smtp.gmail.com';
	$mail->Port = 465; 
        $mail->Username   = "me@gmail.com";
        $mail->Password   = "password";

Same results. I don't know why this shouldn't work now. As I was working out the bugs in this bit of code - process.php was returning 0 and I was getting the popup error message so now I must be connecting to gmail... hmmmm now I have a headache.
 
Okay! This works...

Code:
<?php

require_once("phpmailer/class.phpmailer.php");

$mail = new PHPMailer();
 
$mail->IsSMTP();                                      // set mailer to use SMTP
$mail->Host = "mail.global.frontbridge.com";          // specify main and backup server
$mail->Port = 25;
$mail->From = "evil8@mymailaddress1.com";
$mail->FromName = "Webmaster";
$mail->AddAddress("evil8@mymailaddress2.com");                  // Email to 
$mail->WordWrap = 50;                                 // set word wrap to 50 characters
$mail->IsHTML(true);                                  // set email format to HTML
 
$mail->Subject = "PHPMailer Test";
$mail->Body    = "This is the HTML message body <b>in bold!</b>";
$mail->AltBody = "This is the body in plain text for non-HTML mail clients";
 
if(!$mail->Send())
{
   echo "Message could not be sent. <p>";
   echo "Mailer Error: " . $mail->ErrorInfo;
   exit;
}
 
echo "Message has been sent";
?>

Now why don't I get an email when I incorporate this into the process.php code?

Code:
require_once("phpmailer/class.phpmailer.php");

$mail = new PHPMailer();
 
$mail->IsSMTP();                                      // set mailer to use SMTP
$mail->Host = "mail.global.frontbridge.com";          // specify main and backup server
$mail->Port = 25;
$mail->From = "gdianoski@mediqwest.com";
$mail->FromName = "Webmaster";
$mail->AddAddress("gdianoski@sauterinsurance.com");                  // Send email to 
$mail->WordWrap = 50;                                 // set word wrap to 50 characters
$mail->IsHTML(true);                                  // set email format to HTML

//Retrieve form data. 
//GET - user submitted data using AJAX
//POST - in case user does not support javascript, we'll use POST instead

... same code as above from here down .....

any suggestions?

Thanks!
 
I'm back to work on this this morning...

I'm getting an unexpected $end on line 83 -

Code:
    //send the mail
    $result = sendmail($to, $subject, $message, $from);
    
    //if POST was used, display the message straight away
    if ($_POST) {
        if ($result) echo 'Thank you! We have received your message.';
        else echo 'Sorry, unexpected error. Please try again later';
        
    //else if GET was used, return the boolean value so that 
    //ajax script can react accordingly
    //1 means success, 0 means failed
    } else {
[red]        echo $result;    [/red]
    }

//if the errors array has values
} else {
    //display the errors message
    for ($i=0; $i<count($errors); $i++) echo $errors[$i] . '<br/>';
    echo '<a href="info.php">Back</a>';
    exit;
}

 
Sorry... continueing from above -

It looks to me that after echo $result there is an close curly bracket and then two lines later I have } else {

When I remove one of the close curly brackets I get a t_else on that line. So there is something really going on with the code in this section.
 
For a number of years I have used the alternative control syntax in lieu of curly braces. it really helps when finding mismatches.

i also use a decent code editor that tells me whenever I miss off the end of a control structure.
 
I'm just learning the alternative control syntax. I actually got a form mailer to work. Not the one posted above, but something that has better input validation in it that also sends me the user's ip for spam control.
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top