Passing dynamic data from JavaScript to PHP - php

I have somewhat of an "order" page set up that allows people to select items for purchase. When they hit "order" it takes them to a page that allows them to select details for each item drom dynamically populated drop downs. These drop downs are in a loop so that each item has its own set.
This is where my issue starts. If there is only one item on the order page it works perfectly. All the selected info from the drop downs is pulled into my PHP script, and it formats it into an email and sends the order to me. If there is more than 1 item in the order, it will only send the last item on the page.
Here is the code for the dropdowns...
<form name="mediumselect">
<table>
<tr>
<td>
<select name="sel" onchange="selFormat(this);" style="width:200px">
<option value="">-Please select delivery format-</option>
<option value="File">File</option>
<option value="Tape">Tape</option>
<option value="Disc">Disc</option>
</select>
</td>
<td>
<select name="formats" onchange="selRate(this)" style="width:150px">
</select>
</td>
<td>
<select name="framerate" onchange="selColor(this)" style="width:150px">
</select>
</td>
<td>
<select name="color" style="width:150px">
</select>
</td>
</table>
</form>
Here is the PHP...
<?php
$asset = $_REQUEST['assetname'];
$medium = $_REQUEST['sel'];
$type = $_REQUEST['formats'] ;
$framerate = $_REQUEST['framerate'] ;
$color = $_REQUEST['color'] ;
$body = <<<EOD
Asset Name: $asset
Asset format: $medium
Format Type: $type
Frame Rate/Resolution: $framerate
Codec or Color Subsample: $color
EOD;
$results = <<<EOD
<html>
<head>
<title>sent message</title>
<style type="text/css">
</style>
</head>
<div align="center">One your order is submitted, a confirmation email will be sent to above email with order details.</div>
</div>
</body>
</html>
EOD;
function spamcheck($field)
{
//filter_var() sanitizes the e-mail
//address using FILTER_SANITIZE_EMAIL
$field=filter_var($field, FILTER_SANITIZE_EMAIL);
//filter_var() validates the e-mail
//address using FILTER_VALIDATE_EMAIL
if(filter_var($field, FILTER_VALIDATE_EMAIL))
{
return TRUE;
}
else
{
return FALSE;
}
}
if (isset($_REQUEST['email']))
{
//if "email" is filled out, proceed
//check if the email address is invalid
$mailcheck = spamcheck($_REQUEST['email']);
if ($mailcheck==FALSE)
{
echo "Invalid input";
} else {
//send email
global $body;
global $results;
$email = $_REQUEST['email'] ;
mail("~~~#gmail.com", "Subject: INCOMING ORDER", $body, "From: $email" );
echo "$results";
}
} else {//if "email" is not filled out, display the form
echo "<form method='post' action='mailform.php'>
Email: <input name='email' type='text'><br>
Subject: <input name='subject' type='text'><br>
Message:<br>
<textarea name='message' rows='15' cols='40'>
</textarea><br>
<input type='submit'>
</form>";
}
?>
I am still new to PHP and if there is a better way to go about doing this I would be grateful for the advice.

I would recommend putting all the $body values into a single string. So first loop through every item and just add to the string $body using PHP concatenation ($body . =). Currently you are only retrieving one value. Perhaps change the names of your fields by looping through them for how many items there are ++ a number following the name in order to loop through those _REQUESTS for that those fields in put them into you $body .= string for email.

Related

Email validation using PHP

I have a form for which i am trying to validate the email address. If the email address is incorrect i want a value of "Please type a valid email address." to be returned into the "email" input box on the form. What am i doing wrong? No validation is taking place. I receive the form information at my email and once submitted the user is sent to the "Thank you" page, but no validation. I can put anything in the "email" input and the form will submit.
<form action="../php/contact.php" method="post">
<p>First Name:</p>
<input class="box_style" type="text" name="first_name" required maxlength="20" />
<p>Last Name:</p>
<input class="box_style" type="text" name="last_name" required maxlength="25" />
<p>Email:</p>
<input class="box_style" type="text" name="email" required maxlength="50" />
<p>Contact Number (optional):</p>
<input class="box_style" type="text" name="contact_number" maxlength="12" />
<p>How did you find us?</p>
<select class="box_style" name="how" required>
<option value="choose">Select...</option>
<option value="referal">Referal</option>
<option value="website">Website</option>
<option value="search">Search Engine</option>
<option value="card">Business Card</option>
</select>
<p>Enquiries:</p>
<textarea class="box_style" name="inquiries" cols="30" rows="10"></textarea>
<input class="box_style" type="submit" name="submit" value="Submit"/>
</form>
and this is the php
<?php
function test_input($data) {
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
// define variables and set to empty values
$fName = $lName = $email = $cNum = $how = $enquiries = "";
if ($_SERVER["REQUEST_METHOD"] == "POST") {
$fName = test_input($_POST["first_name"]);
$lName = test_input($_POST["last_name"]);
$cNum = test_input($_POST["contact_number"]);
$how = test_input($_POST["how"]);
$enquiries = test_input($_POST["enquiries"]);
$email = test_input($_POST["email"]);
if(!filter_var($email, FILTER_VALIDATE_EMAIL)) {
print "<p>Please type a valid email address.</p>";
header("Location: www.mysite/thankyou.com");
}};
$email_from = 'my#email.com';
$email_subject = "New Inquiry";
$email_body = "You have received a new message from" ." ". "$fName" ." ". "$lName" ."\n".
"$inquiries"."\n".
"Referal Type:" ." ". "$how" ."\n".
"Contact Number:" ." ". "$cNum" ."\n";
$to = "my#email.com";
$headers = "From: $email_from \r\n";
$headers .= "Reply-To: $email \r\n";
mail($to,$email_subject,$email_body,$headers);
?>
Thank You
Here's a simplified version of the OP's code that demonstrates how to display the error message by having the action attribute of the form be the same url as that which displays the form. The code also exemplifies some nice touches for the user:
<?php
include("php4myform.php");
?>
<html>
<head>
<title>Email Validate</title>
</head>
<body>
<form action="<?php echo htmlspecialchars($_SERVER['PHP_SELF']); ?>" method="POST">
<label for="email">Email: </label>
<input id="email" name="email" required maxlength="50" value="<?php echo $e_mess; ?>">
<input type="submit" name="submit" value="Submit">
<input type="reset" id="clear" value="clear">
</form>
<script src="myJS4forms.js"></script>
</body>
</html>
php4myform.php:
<?php
$e_mess = "";
if ( isset($_POST['submit']) && $_POST != null) {
$tainted_email = trim($_POST["email"]);
$sanitized_email = filter_var($tainted_email, FILTER_SANITIZE_EMAIL);
if( !filter_var( $sanitized_email, FILTER_VALIDATE_EMAIL ) ) {
$e_mess = "Please type a valid email address.";
}
else
{
// Data is good to go.
}
}
myJS4forms.js:
var d = document;
d.g = d.getElementById;
var email = d.g("email");
var reset = d.g("clear");
function selFoc(obj){
obj.focus();
obj.select();
}
window.onload = function() {
selFoc( email );
};
reset.addEventListener("click",function(e) {
e.preventDefault();
email.value=null;
selFoc( email );
});
A few notes:
The drawback of testing with $_SERVER["REQUEST_METHOD"] is that the user might submit an empty form. Therefore, the PHP code in this example tests to see if the form was submitted and if the POST contains any data.
It is ill-advised to use htmlspecialchars() with filter_var and the parameter FILTER_EMAIL_SANITIZE; see this discussion and here, too. The code employs htmlspecialchars() instead to safeguard $_SERVER['PHP_SELF'] -- basis: this article.
I removed stripslashes() since magic quotes are deprecated and gone as of PHP5.4; see the online Manual. (Using addslashes() to escape data is inadvisable -- better to use mysqli_real_escape_string().) Also, filter_var with FILTER_SANITIZE_EMAIL will remove any slashes (see Manual).
If you redirect the user using a "header()" function, you need to stop the execution of the script. So the correct way would be something like this:
$email = test_input($_POST["email"]);
if(!filter_var($email, FILTER_VALIDATE_EMAIL)) {
print "<p>Please type a valid email address.</p>";
header("Location: www.mysite/thankyou.com");
exit();
}
If you don't terminate the script, it will continue executing the rest of the file.
Secondly, if you print something to the user and immediately redirect him elsewhere, he will never see the message. If you want to do a redirection and show the message there, you need to store the message first, probably in a session variable, and then show it on the "landing page".

PHP Contact form not returning errors, but I am still not receiving any emails

Forgive me if this is a stupid question, but I am pretty new to PHP and I am running into some issues. I am trying to build a contact form with HTML, CSS, and PHP, but I can't seem to get my PHP form to send the contents of the form to my email address. This is what the code looks like for the HTML:
<div id="contact-form">
<ul>
<li><button id="quote" class="button1">Project Quote</button></li>
</ul>
<form class= "emai" action="mailer.php" method="post">
<p>Have a project in mind? Fill in the form for a quote!</p>
<div>
<p><label for="name">What can I call you? <span>*</span></label></p>
<input type="text" id="name" name="name">
</div>
<div>
<p><label for="email">What is your email? <span>*</span></label></p>
<input type="email" name="email" id="email">
</div>
<div>
<p><label for="type">Type of Project? <span>*</span></label></p>
<select id="type" name="type">
<option value="logo">Logo Design</option>
<option value="web dev">Website/WebApp Dev</option>
<option value="other">Other</option>
</select>
</div>
<div>
<p><label for="purpose">What is the main purpose of your project? <span>*</span></label></p>
<textarea id="purpose" name="purpose"></textarea>
</div>
<div>
<p><label for="features">Any extra features?</label></p>
<textarea id="features" name="features"></textarea>
</div>
<input class="button1" type="submit" value="submit">
</form>
</div>
And in a separate doc called "mailer.php" this is what the code looks like:
<?php
/* Set e-mail recipient */
$myemail = "christopher.kenrick#gmail.com";
$subject = "Project Request";
/* Check all form inputs using check_input function */
$name = check_input($_POST['name'], "Enter your name");
$email = check_input($_POST['email']);
$type = check_input($_POST['type'], "Select a type of project");
$purpose = check_input($_POST['purpose'], "What is the purpose of your project?");
/* If e-mail is not valid show error message */
if (!preg_match("/([\w\-]+\#[\w\-]+\.[\w\-]+)/", $email))
{
show_error("E-mail address not valid");
}
/* Let's prepare the message for the e-mail */
$message = "
Name: $name
E-mail: $email
Type: $type
Purpose: $purpose
Features: $features
Message:
$message
";
/* Send the message using mail() function */
mail($myemail, $subject, $message);
/* Redirect visitor to the thank you page */
header('Location: thanks.html');
exit();
/* Functions we used */
function check_input($data, $problem='')
{
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
if ($problem && strlen($data) == 0)
{
show_error($problem);
}
return $data;
}
function show_error($myError)
{
?>
<html>
<body>
<p>Please correct the following error:</p>
<strong><?php echo $myError; ?></strong>
<p>Hit the back button and try again</p>
</body>
</html>
<?php
exit();
}
?>
Here is a link to my website if it will help. Can someone tell me what it is I am doing wrong?
Your code lacks proper mail headers. (and originally had a missing subject variable which you now added).
Add and modify your present mail() function with the following code, otherwise mail will be sent directly to Spam as it did for my test.
$headers = 'From: ' . $email . "\r\n";
mail($myemail, $subject, $message, $headers);
with a conditional statement:
if(mail($myemail, $subject, $message, $headers)){
echo "Success"; } else{ echo "There was a problem.";}
After running sudo apt-get install sendmail I finally started receiving the contents of the contact form. This solution should work for those using DigitalOcean as their host.

Not picking up clients email address to send using MAIL function

<html>
<head>
<title>Max Design contact page</title>
<link href="mdstyle1.css" rel="stylesheet" type="text/css" />
</head>
<body>
<div class="container">
<?php
$required = array("firstName" => "First Name",
"surname" => "Surname",
"email" => "Email Address",
"telephone" => "Telephone");
foreach($required as $field => $label) {
if (!$_POST[$field]) {
$warnings[$field] = "*";
}
}
if ($_POST["firstName"] &&
!ereg("[a-zA-Z]", $_POST["firstName"]))
$warnings["firstName"] = "Please check First Name for errors";
if ($_POST["surname"] &&
!ereg("[a-zA-Z]", $_POST["surname"]))
$warnings["surname"] = "Please check Surname for errors";
if ($_POST["email"] &&
!ereg("^[^#]+#([a-z\-]+\.)+[a-z]{2,4}$", $_POST["email"]))
$warnings["email"] = "Please check email for errors";
if ($_POST["telephone"] &&
!ereg("[0-9]", $_POST["telephone"]))
$warnings["telephone"] = "Please check Telephone for errors";
if (count($warnings) > 0) {
// sets the description of the sections of the form and must have an entry for each form element
$description = array();
$description{"firstName"} = "First Name";
$description{"surname"} = "Surname";
$description{"telephone"} = "Telephone Number";
$description{"email"} = "Email Address";
?>
<div class="main-paragraph">
<form method="POST" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>">
<br />
<div class="warnings"> * Please fill in these boxes </div>
<br />
<br />
<TABLE BORDER=0>
<TR>
<TD><label>First Name</label>
</TD><TD><INPUT TYPE=TEXT SIZE=30 NAME="firstName"
VALUE="<?php echo $_POST["firstName"];?>"></TD>
<TD><div class="warnings"><?php echo $warnings["firstName"];?></div></TD>
</TR>
<TR>
<TD><label>Surname</label>
</TD><TD><INPUT TYPE=TEXT SIZE=30 NAME="surname"
VALUE="<?php echo $_POST["surname"];?>"></TD>
<TD><div class="warnings"><?php echo $warnings["surname"];?></div></TD>
</TR>
<TR>
<TD><label>Email Address</label>
</TD>
<TD><INPUT TYPE=TEXT SIZE=30 NAME="email"
VALUE="<?php echo $_POST["email"];?>"></TD>
<TD><div class="warnings"><?php echo $warnings["email"];?></div></TD>
</TR>
<TR>
<TD><label>Telephone</label>
</TD>
<TD><INPUT TYPE=TEXT SIZE=15 NAME="telephone"
VALUE="<?php echo $_POST["telephone"];?>"></TD>
<TD><div class="warnings"><?php echo $warnings["telephone"];?></div></TD>
</TR>
</TABLE>
<br />
<INPUT TYPE=SUBMIT VALUE="Send Enquiry">
</FORM>
</div> <!-- end of main paragraph -->
<?php
}
else { // start of send section
//stuff that goes to the enquirer
$clients_email = "From: sales#rmrc.co.uk";
$headers2 = "From: simon#maxdesign.org.uk";
$subject2 = "Thank you for contacting MAX Design";
$autoreply = "Thank you for contacting MAX Design. We will get back to you as soon as possible,
\n usualy within 48 hours. If you have any more questions,
\n please consult our website at www.maxdesign.org.uk/index";
//prints out each field's title and contents in turn each on new line
$body = "A quote request from the website:\n\n";
foreach($_POST as $description => $value) {
$body .= sprintf("%s = %s\n", $description, $value);
}
mail($email, $subject2, $autoreply, $headers2);
mail("sim.on#hotmail.co.uk", "MAX Design website enquiry", $body, $email);
header( "Location: http://www.maxdesign.org.uk/thank-you-for-quote-max-design.html" );
} //end of send section
?>
</div><!--end of container/wrapper div -->
</body>
</html>
I am trying to send a fairly crudely formatted email (I am trying to get the email formatted a little bit using the $description variable but that isn't working either) from the clients website but the script won't send it to the clients email using the $email string so am having no luck. Have been at this for days now so any help really appreciated.
Simon
You are sending a variable called $email to your mail() which is not at all defined in the code. That is why your mail is not being sent. See below
mail($email, $subject2, $autoreply, $headers2);
//^^^^^ Undefined variable
Solution : Set the $email to some email.

How to get php echo and die messages to work with jQuery notice plugin

I've created a contact form and it's set up to send the form contents via a mail.php file. At the moment it brings up a success/error message on a new blank page via echo and die respectively, but I want to have some kind of notification that pops up on the current page instead.
The solution I'd like to use is http://www.sandbox.timbenniks.com/projects/jquery-notice/, but the demo on that site uses an example of adding the notification to a button. What I need to do is add the notification in place of the echo or die output message. Is this possible?
Here's the mail.php code I'm using...
<?php $name = $_POST['name'];
$email = $_POST['email'];
$phone = $_POST['phone'];
if (isset($_POST['service'])) {
$service = $_POST['service'];
// $service is an array of selected values
}
$message = $_POST['message'];
$formcontent=" Message received from wwww.jhnormanandsons.co.uk: \n \n From: $name \n Phone: $phone \n \n Service required: $service \n \n Message: $message";
$recipient = "jasonbradberry#gmail.com";
$subject = "You have a new message from $name";
$mailheader = "From: $email \r\n";
mail($recipient, $subject, $formcontent, $mailheader) or die("Error!");
echo ("Thank you for your message. We'll be in touch as soon as we can.");
?>
Here's the form HTML...
<form id="contact-form" method="post" action="mail.php" name="jh_contact">
<input type="text" id="name" name="name" placeholder="Name" required />
<input type="email" id="email" name="email" placeholder="Email" required />
<input type="tel" id="phone" name="phone" placeholder="Phone" required />
<textarea id="message" name="message" placeholder="Message" required ></textarea>
<select name="service">
<option>Service required</option>
<option value="MOT">MOT</option>
<option value="Service / repairs">Service / repairs</option>
<option value="Cars for sale">Cars for sale</option>
<option value="Welding">Welding</option>
<option value="Exhausts">Exhausts</option>
<option value="Tyres">Tyres</option>
<option value="Brakes">Brakes</option>
<option value="Diagnostics">Diagnostics</option>
<option value="Vehicle checks">Vehicle checks</option>
<option value="Courtesy car">Courtesy car</option>
<option value="Advice">Advice</option>
<option value="Other">Other</option>
</select>
<input type="submit" value="Send" id="submit-button" name="submit" />
</form>
Thanks!
I'd have the form work with JavaScript disabled too, and then use jQuery to POST the form to the page and parse any normal success messages that way.
<?php
if (isset($_POST['send'])) {
// process form
if ($sent === true) {
$alert_class = 'success';
$alert_test = 'Your enquiry was sent successfully.';
}
else {
$alert_class = 'error';
$alert_text = 'There was an error sending your enquiry.';
}
}
?>
<!DOCTYPE html>
<html>
<body>
<?php if (isset($alert_text)): ?>
<div class="alert <?php echo $alert_class; ?>">
<p><?php echo $alert_text; ?></p>
</div>
<?php endif; ?>
<form action="" method="post" id="contact-form">
<!-- your form -->
</form>
</body>
</html>
And then the jQuery:
(function($) {
$('#contact-form').submit(function() {
$.post($(this).attr('action'), $(this).serialize(), function(response) {
var alert_text = $(response).find('.alert').text();
alert(alert_text);
});
return false;
});
})(jQuery);
Hope that helps.
Use Jquery post to submit your form. and get the notification message to display as json...
http://api.jquery.com/jQuery.post/
search for this line to submit your form using jquery
"Example: send form data using ajax requests"...
on response.. write this code(taken from the notification link u added)
jQuery.noticeAdd({
text: data , //ur notification msg
stay: true
});

How to send multiple checkbox responses from HTML form via php?

I have set up a contact form, and set it to email the response to an email account. Part of the form is a series of checkboxes, and I need to get these to display in the email as a list. This is the code I have below, which at the moment returns 'Array' instead of the values of the checkboxes. Any suggestions?
HTML:
<h3>Service required:</h3>
<input type="text" id="name" name="name" placeholder="Name" required />
<input type="email" id="email" name="email" placeholder="Email" required />
<input class="check-box styled" type="checkbox" name="service[]" value="Service / repairs" /><label> Service / repairs</label>
<input class="check-box styled" type="checkbox" name="service[]" value="MOT" /><label> MOT</label>
<input class="check-box styled" type="checkbox" name="service[]" value="Cars for sale" /><label> Cars for sale</label>
Here's the php:
<?php
if (isset($_POST['service'])) {
$service = $_POST['service'];
// $service is an array of selected values
}
$formcontent= "From: $name \n Service(s) required: $service \n";
$recipient = "name#email.com";
$subject = "You have a new message from $name";
$mailheader = "From: $email \r\n";
mail($recipient, $subject, $formcontent, $mailheader) or die("Error!");
echo "Thank You! We will get back to you as soon as we can.";
?>
Thanks,
Jason
You should join (for example implode with ', ') your array elements to a string.
<?php
$formcontent= "From: $name \n Service(s) required: ".implode(", " ,$service)." \n";
?>
Why don't you loop through the array to get the desired results into a String?
if (isset($_POST['service'])) {
$service = $_POST['service'];
// $service is an array of selected values
$service_string = "";
for($i=0;$i<count($service);$i++)
{
if($i!=0)
{
$service_string = $service_string . ", ";
}
$service_string = $service_string . $service[$i];
}
}
You will then get an output of a comma separated list of each ticked item as $service_string.
Since several checkboxes are stored in $_POST['service'], it is an array itself and has become two-dimensional. Its different indexes are accessible like this: $_POST['service'][0].
To do something with $_POST['service'], you can use foreach to loop through all indexes:
foreach($_POST['service'] as $post){
//Do stuff here
}
Alternatively, use implode() to simply concatenate all indexes.
Your input type checkbix must have unique names. Otherwise last checkbox will be found in $_POST. Or you can loop through as discuss above. Make your email html format and write a string of html to $formcontent. e.g.
$formcontent = "<html><head></head><body>";
$formcontent .= "<ul><li>".$_POST["checkbox1"]."</li>";
$formcontent .= "<li>".$_POST["checkbox2"]."</li>";
$formcontent .= "</ul></body></html>";
To write email in html format see mail function on php website.

Categories