I have this simple form code here
<?php
$EmailFrom = "form#form.com";
$EmailTo = "s#outlook.com";
$Subject = "Form";
$Name = Trim(stripslashes($_POST['Name']));
$Budget = Trim(stripslashes($_POST['Budget']));
$Email = Trim(stripslashes($_POST['Email']));
$Message = Trim(stripslashes($_POST['Message']));
// validation
$validationOK=true;
if (!$validationOK) {
print "<meta http-equiv=\"refresh\" content=\"0;URL=error.htm\">";
exit;
}
// prepare email body text
$Body = "";
$Body .= "Name: ";
$Body .= $Name;
$Body .= "\n";
$Body .= "Budget: ";
$Body .= $Budget;
$Body .= "\n";
$Body .= "Email: ";
$Body .= $Email;
$Body .= "\n";
$Body .= "Message: ";
$Body .= $Message;
$Body .= "\n";
// send email
$success = mail($EmailTo, $Subject, $Body, "From: <$EmailFrom>");
// redirect to success page
if ($success){
print "<meta http-equiv=\"refresh\" content=\"0;URL=contactthanks.php\">";
}
else{
print "<meta http-equiv=\"refresh\" content=\"0;URL=error.htm\">";
}
?>
And I was wondering how to make the from address in the top the same as the one submitted.
If I understand correctly, you can do away entirely with this variable:
$EmailFrom = "form#form.com";
And this revised mail() function should do what you're asking:
// send email
$success = mail($EmailTo, $Subject, $Body, "From: " . $Email . "\r\n");
Note I've used the following variable you've already declared:
$Email = Trim(stripslashes($_POST['Email']));
Related
I want to redirect the user to another page only after displaying a success message. The code below redirects to the another page even if the page is refreshed without submitting any data.
Code Snippet
<?php
// We will store our status message later
$message = '';
// Let's check form submitted
if( isset( $_POST['action'] ) && $_POST['action'] == 'submit' ) {
$name = $_POST['name'];
$email = $_POST['email'];
$phone = $_POST['number'];
$message_text = $_POST['address'];
if (isset($_POST['action']))
{
// Validate required fields
if( $name == '' || $email == '' || $message_text == '' ){
$message = "<p class=\"error\">Please fill out all required fields.</p>";
}
// send email after validation
else {
// Email will be sent at this email
$mailto = 'nepstarditsolutions#gmail.com';
// Let's create html email format
// (You can use html in this email format)
// Email headers
$headers = "From: " . strip_tags( $email ) . "\r\n";
$headers .= "Reply-To: ". strip_tags( $email ) . "\r\n";
$headers .= "MIME-Version: 1.0\r\n";
$headers .= "Content-Type: text/html; charset=ISO-8859-1\r\n";
// Email body
$message = "<html><body>";
$message .= "<h3>Contact Info: </h3>";
$message .= "<p><strong>Name: </strong> ". strip_tags( $name ) . "</p>\r\n";
$message .= "<p><strong>Email: </strong> ". strip_tags( $email ) . "</p>\r\n";
$message .= "<p><strong>Contact Number: </strong> ". strip_tags( $phone ) . "</p>\r\n";
$message .= "<p><strong>Alternate Email: </strong> ". strip_tags( $_POST['altemail'] ) . "</p>\r\n";
$message .= "<p><strong>Hosting Package: </strong> ". strip_tags( $_POST['cradio'] ) . "</p>\r\n";
$message .= "<p><strong>Address: </strong>". strip_tags( $message_text ) . "</p>\r\n";
$message .= "</body></html>";
// Email subject
$subject = "Contact Info from ".$name;
// Send email
$mail_status = #mail( $mailto, $subject, $message, $headers );
if( $mail_status ){
$message = '<div class="alert alert-success">Quotation submitted Successfully ! </div>';
}
else {
$message = '<div class="alert alert-danger">Error in sending the Quotation ! </div>';
}
}
}
}
?>
I need help in 2 things
Success message should be displayed for 2 seconds (before the redirect).
How to redirect using JS in php?
Standard "vanilla" JavaScript way to redirect a page
You can use the code below to redirect the user after form submission code.
if( $mail_status ){
echo "
<script>
setTimeout(function() {
window.location = 'http://www.example.com/newlocation';
}, 2000);
</script>
";
}
MDN web docs on how setTimeout works
Hope it helps!
$id = $_POST['id'];
$to="codieboi#mail.com";
$msg1="done";
$email_subject = "View Cateloge Request";
$headers = 'MIME-Version: 1.0' . "\r\n";
$headers .= 'Content-type: text/html; charset=iso-8859-1' . "\r\n";
$headers .= 'X-MSMail-Priority: High'. "\r\n";
$headers = 'From: '.$_POST['email']."\r\n".
'X-Mailer: PHP/' . phpversion();
$email_message .= "Name: ".$_POST['fname']."\n";
$email_message .= "Email: ".$_POST['email']."\n";
$email_message .= "Phone: ".$_POST['phone']."\n";
$email_message .= "Phone: ".$_POST['message']."\n";
#mail($to, $email_subject, $email_message, $headers);
$link = the_field('upload_file', $id);
echo '<script type="text/javascript">var url="_________";var win = window.open(url, "_blank");win.focus();</script>';
I store a url dynamically to the variable "link". I want to open up it in a new tab, once the mail is send. This is the code I have written. I need to place url in the _____________.
Please help.
If you store url to variable link, just use it:
echo "<script type='text/javascript'>var url='". $link."';var win = window.open(url, '_blank');win.focus();</script>";
On a Linux server, I have an ajax form that gets posted to a js script, which in turn posts to a php routine for sending a web site email contact form (Styleshout-Puremedia template). I know the post is occurring to js, and to the php page. I get an httpd server error on the php page that "$Error is undefined". However if I define it as NULL or '' it exists and therefore doesn't pass the test "if (!$Error)". If I create a hard-coded php script using the mail function, the e-mail works so php and sendmail are all configured properly. Can someone help as to why this php script doesn't work, or how to fix the "$Error" error?
PHP code:
<?php
// Replace this with your own email address
$siteOwnersEmail = 'info#mydomain.com';
if($_POST) {
$fname = trim(stripslashes($_POST['contactFname']));
$lname = trim(stripslashes($_POST['contactLname']));
$email = trim(stripslashes($_POST['contactEmail']));
$subject = trim(stripslashes($_POST['contactSubject']));
$contact_message = trim(stripslashes($_POST['contactMessage']));
// Check First Name
if (strlen($fname) < 2) {
$error['fname'] = "Please enter your first name.";
}
// Check Last Name
if (strlen($lname) < 2) {
$error['lname'] = "Please enter your last name.";
}
// Check Email
if (!preg_match('/^[a-z0-9&\'\.\-_\+]+#[a-z0-9\-]+\.([a-z0-9\-]+\.)*+[a-z]{2}/is', $email)) {
$error['email'] = "Please enter a valid email address.";
}
// Check Message
if (strlen($contact_message) < 15) {
$error['message'] = "Please enter your message. It should have at least 15 characters.";
}
// Subject
if ($subject == '') { $subject = "Contact Form Submission"; }
// Set Name
$name = $fname . " " . $lname;
// Set Message
$message = "Email from: " . $name . "<br />";
$message .= "Email address: " . $email . "<br />";
$message .= "Message: <br />";
$message .= $contact_message;
$message .= "<br /> ----- <br /> This email was sent from your site's contact form. <br />";
// Set From: header
$from = $name . " <" . $email . ">";
// Email Headers
$headers = "From: " . $from . "\r\n";
$headers .= "Reply-To: ". $email . "\r\n";
$headers .= "MIME-Version: 1.0\r\n";
$headers .= "Content-Type: text/html; charset=ISO-8859-1\r\n";
if (!$error) {
ini_set("sendmail_from", $siteOwnersEmail); // for windows server
$mail = mail($siteOwnersEmail, $subject, $message, $headers);
if ($mail) { echo "OK"; }
else { echo "Something went wrong. Please try again."; }
} # end if - no validation error
else {
$response = (isset($error['fname'])) ? $error['fname'] . "<br /> \n" : null;
$response .= (isset($error['lname'])) ? $error['lname'] . "<br /> \n" : null;
$response .= (isset($error['email'])) ? $error['email'] . "<br /> \n" : null;
$response .= (isset($error['message'])) ? $error['message'] . "<br />" : null;
echo $response;
} # end if - there was a validation error
}
?>
Thanks for your help!!
-Rob
You can always just initialize $error as
$error = [];
and then check for errors by
if(count($errors) === 0){
//no errors
}
Or, just use if(!isset($error)){//no errors}
I wrote this script which doesn't send the data from the AJAX to the PHP file. I debugged it with logging the data that's in the form before it ran through the AJAX function. It gave me this data:
Form: name=jim&email=info%40test.com
However, I get an empty alert and I receive an empty e-mail.
HTML
<form name="form" id="form" class="form" method="post">
<input type="text" class="text border" name="name" id="name" placeholder="Name" />
<input type="text" class="text" name="email" id="email" placeholder="E-mail" />
<input type="submit" class="button" value="Submit" />
</form>
JS
jQuery(function(){
jQuery('#form').submit(function(event){
event.preventDefault();
jQuery.ajax({
type: "POST",
url: "includes/post.php",
data: jQuery('#form').serialize(),
success: function(data){
jQuery("#form").addClass("inactive");
jQuery("#message").addClass("active");
alert(data);
}
});
});
});
PHP
<?php
if ($_SERVER["REQUEST_METHOD"] == "POST") {
$name = mysql_real_escape_string($_POST["name"]);
$email = mysql_real_escape_string($_POST["email"]);
$to = "test#hidden.com";
$message = '
<html>
<body>
<p>
<strong>Name: </strong> '.$name.' <br/>
<strong>E-mail: </strong> '.$email.' <br/>
</p>
</body>
</html>
';
$subject = 'New entry: '.$name.', '.$email;
$headers .= "From: ".$name." ".$$email."\r\n";
$headers .= "X-Mailer: PHP's mail() Function\n";
$headers .= "MIME-Version: 1.0\r\n";
$headers .= "Content-Type: text/html; charset=ISO-8859-1\r\n";;
mail($to, $subject, $message, $headers);
}
?>
Try the below code,
Update your PHP with the below,
if ($_SERVER["REQUEST_METHOD"] == "POST") {
$name = htmlspecialchars($_POST["name"]);
$email = htmlspecialchars($_POST["email"]);
echo $name;// this will see in your response
$to = "test#gmail.com";
$message = '
<html>
<body>
<p>
<strong>Name: </strong> ' . $name . ' <br/>
<strong>E-mail: </strong> ' . $email . ' <br/>
</p>
</body>
</html>
';
$subject = 'New entry: ' . $name . ', ' . $email;
$headers = "From: " . $name . " " . $email . "\r\n";
$headers.= "X-Mailer: PHP's mail() Function\n";
$headers.= "MIME-Version: 1.0\r\n";
$headers.= "Content-Type: text/html; charset=ISO-8859-1\r\n";;
mail($to, $subject, $message, $headers);
}
Nothing is being returned from your php, and you need some form of server side validation, here is a complete code you can use:
header('Cache-Control: no-cache, must-revalidate');
header('Expires: Mon, 26 Jul 1997 05:00:00 GMT');
header('Content-type: application/json');
$admin_email = 'your#yourdomain.com'; // Your Email
$message_min_length = 5; // Min Message Length
class Contact_Form{
function __construct($details, $email_admin, $message_min_length){
$this->name = stripslashes($details['name']);
$this->email = trim($details['email']);
$this->subject = 'Contact from Your Website'; // Subject
$this->message = stripslashes($details['message']);
$this->email_admin = $email_admin;
$this->message_min_length = $message_min_length;
$this->response_status = 1;
$this->response_html = '';
}
private function validateEmail(){
$regex = '/^([\w-]+(?:\.[\w-]+)*)#((?:[\w-]+\.)*\w[\w-]{0,66})\.([a-z]{2,6}(?:\.[a-z]{2})?)$/i';
if($this->email == '') {
return false;
} else {
$string = preg_replace($regex, '', $this->email);
}
return empty($string) ? true : false;
}
private function validateFields(){
// Check name
if(!$this->name)
{
$this->response_html .= '<p>Please enter your name</p>';
$this->response_status = 0;
}
// Check email
if(!$this->email)
{
$this->response_html .= '<p>Please enter an e-mail address</p>';
$this->response_status = 0;
}
// Check valid email
if($this->email && !$this->validateEmail())
{
$this->response_html .= '<p>Please enter a valid e-mail address</p>';
$this->response_status = 0;
}
// Check message length
if(!$this->message || strlen($this->message) < $this->message_min_length)
{
$this->response_html .= '<p>Please enter your message. It should have at least '.$this->message_min_length.' characters</p>';
$this->response_status = 0;
}
}
private function sendEmail(){
$mail = mail($this->email_admin, $this->subject, $this->message,
"From: ".$this->name." <".$this->email.">\r\n"
."Reply-To: ".$this->email."\r\n"
."X-Mailer: PHP/" . phpversion());
if($mail)
{
$this->response_status = 1;
$this->response_html = '<p>Thank You!</p>';
}
}
function sendRequest(){
$this->validateFields();
if($this->response_status)
{
$this->sendEmail();
}
$response = array();
$response['status'] = $this->response_status;
$response['html'] = $this->response_html;
echo json_encode($response);
}
}
$contact_form = new Contact_Form($_POST, $admin_email, $message_min_length);
$contact_form->sendRequest();
You should write echo statement after mail() function. The string written in echo statement will display in alert.
for example : echo "Mail sent successfully";
I have PHP code that help me to other people can be in touch with me and send their opinion to me .
here's my PHP code :
<?php
$to = 'ticket.ritaweb#gmail.com';
$subject = 'Your decision/Opinion';
$name = htmlspecialchars($_REQUEST['name']);
$email = htmlspecialchars($_REQUEST['email']);
$site = htmlspecialchars($_REQUEST['site']);
$mobile = htmlspecialchars($_REQUEST['mobile']);
$nazar = htmlspecialchars($_REQUEST['nazar']);
$sqt = '2164854';
$sqtin = htmlspecialchars($_REQUEST['sqtin']);
if ($sqt === $sqtin) {
function clean_string($string) {
$bad = array("content-
type", "bcc:", "to:", "cc:", "href");
return str_replace($bad, "", $string);
}
$email_message .= "name : " . clean_string($name) . "\n";
$email_message .= "email : " . clean_string($email) . "\n";
$email_message .= "address : " . clean_string($site) . "\n";
$email_message .= "number : " . clean_string($mobile) . "\n";
$email_message .= "opinion : " . clean_string($nazar) . "\n";
$headers = 'From: ' . $mobile . "\r\n" . 'Reply-To: ' . $email . "\r\n" . 'X-Mailer:
PHP/' . phpversion();
mail($to, $subject, $email_message, $headers);
}
?>
and I called it with javascript ( ajax ) but I want a code in ajax that help me If my condition in PHP file was FALSE or each of the field was empty , show the message : "Your message was not send, be careful".
and here's my AJAX code :
<script type="text/javascript">
$(document).ready(function() {
$('#submit').click(function() {
$('#submit').attr('value', 'sending...');
$.post("themes/RitaWeb-v1/send.php", $(".rita_form").serialize(),
function(response) {
$('#submit').attr('value', 'sent.');
});
return false;
});
});
</script>
Use PHP to print messages on the page, like
{'status' : 'success'}
if the mail was sent and
{'status' : 'error'}
Then do something based on the output with js.
EDIT:
If you use jQuery.ajax instead of jQuery.post,you can also use the settings argument to let something happen if there ared errors during the request.
More information: http://api.jquery.com/jquery.ajax/
In your code, it would look like this.
PHP:
...
mail($to, $subject, $email_message, $headers);
print('{"status":"success"}');
}
else{
print('{"status":"error"}');
}
And your js:
$.ajax('themes/RitaWeb-v1/send.php').done(function(data){
status = $.parseJSON(data).status;
if(status == 'success'){
// do something
}
else if(ststus == 'error'){
// do something
}
else{
alert('unknown response');
}
});