Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 7 years ago.
Improve this question
I've got a form I have created that is just a simple form with a text box and submit button. The text box is for an email address that an email will be sent to.
Here's my code:
//Get First Name Value
if($is_logged_id && isset($user_data['FirstName'])) $first_name = $user_data['FirstName'];
//Get Last Name Value
if($is_logged_id && isset($user_data['LastName'])) $last_name = $user_data['LastName'];?>
<?php
//Get Phone Number
if($is_logged_id && isset($user_data['Phones'][0]->Number)) $phone_number = $user_data['Phones'][0]->Number;?>
<?php
//Get Last 4 digits of phone number
$last_four = substr($phone_number, -4);
//Add Phone Number to last name
$ref_code = $last_name . $last_four;
?>
<?php
//if "email" variable is filled out, send email
if (isset($_REQUEST['refemail'])) {
$email_from = $first_name . $last_name . "<" . $user_data['EmailAddress'] . ">";
// Headers
$headers = "MIME-Version: 1.0" . "\r\n";
$headers .= "Content-type:text/html;charset=UTF-8" . "\r\n";
$headers .= 'From: ' . $email_from . "\r\n";
//Email information
$refemail = $_REQUEST['refemail'];
$subject = $first_name;
//send email
mail($refemail, $first_name , $refcode , $headers);
//Email response
echo "<p style='padding: 10px;'>Email Response</p>";
}
//if "email" variable is not filled out, display the form
else {
?>
<form method="post">
<label for="refemail" class="control-label col-sm-3 col-md-3 col-xs-12 text-left ">Email Address:</label>
<div class="form-group"></div>
<input name="refemail" type="text" size="50" class="form-control" /><br />
<input type="submit" class="ref-btn" value="Submit" />
</div>
</form>
<?php
}
?>
Everything is working exactly the way I want it to, except it is sending two emails that are exactly the same instead of just one. I've done some searching around and I can't find anything that solves my problem.
I've tried adding the following below the mail() function:
exit("sent");
It still sends two emails.
Is there something wrong with my code or could this be an issue with my host?
Thanks.
I guess the form submit twice, after you refresh the page or you submit the form then refresh.
Here echo "<p style='padding: 10px;'>Email Response</p>";, if refresh, here you will see just one 'Email Response'.
Here is to prevent the refresh submit(Jquery):
$('#form').submit(function(e){
e.preventDefault();
//then do the submit.
});
Or
you can just replace button type for testing
<button type="button">
---------------------------------------------------------
Example of Ajax Post data:
In the form.php:
<script src="http://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form method="post" id='form'>
<label for="refemail" class="control-label col-sm-3 col-md-3 col-xs-12 text-left ">Email Address:</label>
<input name="refemail" id='refemail' type="text" size="50" class="form-control" /><br />
<input type="submit" class="ref-btn" value="Submit" />
</form>
<script>
$(function(){
$('#form').submit(function(e){
e.preventDefault();
data = {
refemail: $('#refemail').val(),
};
$.ajax({
type: "POST",
url: './sendemail.php',
dataType: "html",
timeout: 50000,
data: data,
success: function(data) {
alert(data);
},
error: function(request, status, err) {}
});
});
});
</script>
In the sendemail.php:
<?php
if(isset($_REQUEST['refemail'])){
echo $_REQUEST['refemail'];
//here do the send email
}else{
echo 'No email';
}
?>
Related
Does anyone have an idea of why my HTML form does not submit anything? Once I click the submit button it does nothing? No idea what is going on, have checked everything and can't get my head around it? If anyone might have an idea, it would be really helpful, thanks!
<div class="row">
<div class="col-md-6">
<div class="alert alert-success hidden" id="contactSuccess">
<strong>Success!</strong> Your message has been sent to us.
</div>
<div class="alert alert-danger hidden" id="contactError">
<strong>Error!</strong> There was an error sending your message.
</div>
<form name="register" action="register.php" id="contactForm" type="POST">
<div class="row">
<div class="form-group">
<div class="col-md-6">
<label>First name *</label>
<input type="text" value="" data-msg-required="Please enter your first name." maxlength="100" class="form-control" name="first_name" id="name">
</div>
<div class="col-md-6">
<label>Last name *</label>
<input type="text" value="" data-msg-required="Please enter your last name." maxlength="100" class="form-control" name="last_name" id="name">
</div>
</div>
</div>
<div class="row">
<div class="form-group">
<div class="col-md-12">
<label>Your email address *</label>
<input type="email" value="" data-msg-required="Please enter your email address." data-msg-email="Please enter a valid email address." maxlength="100" class="form-control" name="email_address" id="email">
</div>
</div>
</div>
<div class="row">
<div class="form-group">
<div class="col-md-6">
<label>Username *</label>
<input type="text" value="" data-msg-required="Please enter a valid username." maxlength="100" class="form-control" name="username" id="name">
</div>
<div class="col-md-6">
<label>Contact Number *</label>
<input type="number" value="" data-msg-required="Please enter your mobile number." maxlength="100" class="form-control" name="mobile" id="name">
</div>
</div>
</div>
<div class="row">
<div class="form-group">
<div class="col-md-6">
<label>Date of birth *</label>
<br>
<fieldset class="date">
<select id="date1" name="date1" />
<option>1</option>
<option>2</option>
<option>…</option>
</select>
<select id="date2" name="date2" />
<option>Jan</option>
<option>Feb</option>
<option>Mar</option>
</select>
<select id="date3" name="date3" />
<option>1905</option>
<option>1906</option>
</select>
</fieldset>
</div>
<div class="col-md-6">
<label>Contact Number *</label>
<input type="radio" name="gender" value="Male">Male
<input type="radio" name="gender" value="Female">Female
</div>
</div>
</div>
<div class="row">
<div class="col-md-12">
<input type="submit" name="Submit" value="Register" class="btn btn-lg btn-primary">
</div>
</div>
</form>
</div>
I am using a copy of the contact form on my site for the registration form as it looks so much better, maybe this is one of the reasons ?
Register.php as requested:
<?
include 'core/init.php';
// Define post fields into simple variables
$first_name = mysql_real_escape_string($_POST['first_name']);
$last_name = mysql_real_escape_string($_POST['last_name']);
$email_address = mysql_real_escape_string($_POST['email_address']);
$username = mysql_real_escape_string($_POST['username']);
$mobile = $_POST['mobile'];
$gender = $_POST['gender'];
$date1 = $_POST['date1'];
$date2 = $_POST['date2'];
$date3 = $_POST['date3'];
/* Let's strip some slashes in case the user entered
any escaped characters. */
$first_name = stripslashes($first_name);
$last_name = stripslashes($last_name);
$email_address = stripslashes($email_address);
$username = stripslashes($username);
$gender = stripslashes($gender);
/* Do some error checking on the form posted fields */
if((!$first_name) || (!$last_name) || (!$email_address) || (!$gender) || (!$username)){
if(!$first_name){
header('Location: signup.php?signuperror=2');
}
if(!$last_name){
header('Location: signup.php?signuperror=3');
}
if(!$email_address){
header('Location: signup.php?signuperror=4');
}
if(!$username){
header('Location: signup.php?signuperror=5');
}
if(!$gender){
header('Location: signup.php?signuperror=6');
}
include "signup.php"; // Show the form again!
/* End the error checking and if everything is ok, we'll move on to
creating the user account */
exit(); // if the error checking has failed, we'll exit the script!
}
/* Let's do some checking and ensure that the user's email address or username
does not exist in the database */
$sql_email_check = mysql_query("SELECT email_address FROM users WHERE email_address='$email_address'");
$sql_username_check = mysql_query("SELECT username FROM users WHERE username='$username'");
$email_check = mysql_num_rows($sql_email_check);
$username_check = mysql_num_rows($sql_username_check);
if(($email_check > 0) || ($username_check > 0)){
if($email_check > 0){
header('Location: signup.php?signuperror=7');
unset($email_address);
}
if($username_check > 0){
header('Location: signup.php?signuperror=8');
unset($username);
}
include 'signup.php'; // Show the form again!
exit(); // exit the script so that we do not create this account!
}
/* Everything has passed both error checks that we have done.
It's time to create the account! */
/* Random Password generator.
http://www.phpfreaks.com/quickcode/Random_Password_Generator/56.php
We'll generate a random password for the
user and encrypt it, email it and then enter it into the db.
*/
function makeRandomPassword() {
$salt = "abchefghjkmnpqrstuvwxyz0123456789";
srand((double)microtime()*1000000);
$i = 0;
while ($i <= 7) {
$num = rand() % 33;
$tmp = substr($salt, $num, 1);
$pass = $pass . $tmp;
$i++;
}
return $pass;
}
$random_password = makeRandomPassword();
$db_password = md5($random_password);
// Enter info into the Database.
$info2 = htmlspecialchars($info);
$sql = mysql_query("INSERT INTO users (first_name, last_name, email_address, username, password, gender, date1, date2, date3, signup_date, mobile)
VALUES('$first_name', '$last_name', '$email_address', '$username', '$db_password', '$gender', '$date1', '$date2', '$date3', now(), '$mobile')") or die (mysql_error());
if(!$sql){
header('Location: signup.php?signuperror=9');
} else {
$userid = mysql_insert_id();
// Let's mail the user!
$subject = "BaseCentre Members";
$message = "Dear $first_name $last_name,
Thank you for registering at BaseCentre, http://www.basecentre.co.uk/
You are two steps away from logging in and accessing our exclusive entertainment.
To activate your membership, please click here: http://www.basecentre.co.uk/activate.php?id=$userid&code=$db_password
Once you activate your memebership, you will be able to login with the following information:
Username: $username
Password: $random_password
Thanks!
Base Admin Team.
This is an automated response, please do not reply!";
mail($email_address, $subject, $message, "From: BaseCentre Members<admin#basecentre.co.uk>\nX-Mailer: PHP/" . phpversion());
////// MAIL ADMIN
$subject2 = "BaseCentre New User!";
$message2 = "Dear Admin,
This is a message to alert you that a new user has signed up to BaseCentre.
You can view all details of the new member and all other members direct from the admin control panel at http://basecentre.co.uk/admin.php
Here are the details of the new registered user:
Username: $username
Email Address: $email_address
Thanks!
BaseCentre Automation.
This is an automated response, please do not reply!";
mail('aidan6141#hotmail.co.uk', $subject2, $message2, "From: BaseCentre Members<admin#basecentre.co.uk>\nX-Mailer: PHP/" . phpversion());
header('Location: login.php?loginerror=6');
include 'login.php';
}
?>
JS Script for reference:
/*
Name: View - Contact
Written by: Okler Themes - (http://www.okler.net)
Version: 2.0
*/
(function() {
"use strict";
var Contact = {
initialized: false,
initialize: function() {
if (this.initialized) return;
this.initialized = true;
this.build();
this.events();
},
build: function() {
this.validations();
},
events: function() {
},
validations: function() {
$("#contactForm").validate({
submitHandler: function(form) {
// Loading State
var submitButton = $(this.submitButton);
submitButton.button("loading");
// Ajax Submit
$.ajax({
type: "POST",
url: "php/contact-form.php",
data: {
"name": $("#contactForm #name").val(),
"email": $("#contactForm #email").val(),
"subject": $("#contactForm #subject").val(),
"message": $("#contactForm #message").val()
},
dataType: "json",
success: function (data) {
if (data.response == "success") {
$("#contactSuccess").removeClass("hidden");
$("#contactError").addClass("hidden");
// Reset Form
$("#contactForm .form-control")
.val("")
.blur()
.parent()
.removeClass("has-success")
.removeClass("has-error")
.find("label.error")
.remove();
if(($("#contactSuccess").position().top - 80) < $(window).scrollTop()){
$("html, body").animate({
scrollTop: $("#contactSuccess").offset().top - 80
}, 300);
}
} else {
$("#contactError").removeClass("hidden");
$("#contactSuccess").addClass("hidden");
if(($("#contactError").position().top - 80) < $(window).scrollTop()){
$("html, body").animate({
scrollTop: $("#contactError").offset().top - 80
}, 300);
}
}
},
complete: function () {
submitButton.button("reset");
}
});
},
rules: {
name: {
required: true
},
email: {
required: true,
email: true
},
subject: {
required: true
},
message: {
required: true
}
},
highlight: function (element) {
$(element)
.parent()
.removeClass("has-success")
.addClass("has-error");
},
success: function (element) {
$(element)
.parent()
.removeClass("has-error")
.addClass("has-success")
.find("label.error")
.remove();
}
});
}
};
Contact.initialize();
})();
As well as the post method, input fields should also have a name attribute.
Change this line,
<form name="register" action="register.php" id="contactForm" method="POST">
you must use method="POST" instead of type="POST"
Make sure you submit button is of type submit rather than type button.
If your form is not submitting and you have checked the suggestions in the previous answers then its probably that you have multiple form ending tags, overlapping form tags or incorrectly closed divs.
Here's a checklist for you which are standard and not php purely based, something you could have a look at in case you still experience this issue:
Check you have a valid action element in your form tag
eg: action="/subjects"
Check you have a valid method element (not a type element)
eg: method="post"
Opening and closing <form> tags and a submit button placed within these tags. Make sure that there are no extra divs causing incorrect closing of elements. - DOUBLE CHECK THIS AS IT IS THE MOST COMMON CAUSE OF MANY HEADACHES
Overlapping Form tags. (Make sure that you don't have multiple form closing tags, etc)
post is being sent but there is an error in the backend/server/api which is not returning an error or success message to the browser? (Check Network section or browser after pressing F12)
If your problem still happens then consider trying to use javascript instead of html form submission for instance. By adding an onclick event to a button and writing the form.submit function.
I've never heard of any different form submit errors which are not logged in the console or which you can see in the Network section of your browsers development toolbar. Curious to know of your problem in the end.
The valid attribute for the form is method not type
method = 'post'
Make sure that you have the attribute name on each field.
Example: name="email"
is simple :
type="POST" change with Method="POST"
Also check that your action="register.php" is not being redirected.
For example action="/xyz/register.php" -- register.php should be in the 'xyz' folder.
If register.php is not in the 'xyz' folder and the form is being redirected, it will go to the correct page but lose the form's values (name, email etc).
I have tried to post form data from a React JS rendered form, calling aq php file with the action part of the form... I have uploaded the form and the attached PHP file to my website, but when the form is filled out out submitted, no email is sent, and the url changes back to the homepage with the name of the PHP file tagged on (index.js/contact.php).
Is my code below bad?
Or is this just not possible to do using a combination of React JS and PHP?
contactMe.js
import React, { Component } from 'react';
class ContactMe extends Component {
render() {
return (
<div className='contact-body'>
<div className='contact-right'>
<div className='contact-side'>
<h2 style={{ fontSize: '25px', fontFamily: 'Anton', paddingTop: '10px'}}>
Contact Me
</h2>
<hr />
<div className='contact-list'>
<div className='form'>
<form action="contact.php" method='post'>
<input type="text" name="name" placeholder="Your name..." />
<input type="email" name="email" placeholder="Your email..." />
<textarea name="message" placeholder="Message me..."></textarea>
<input type="submit" value="Submit" />
</form>
</div>
</div>
</div>
</div>
</div>
)
}
}
export default ContactMe;
contact.php
<?php
if (isset($_POST['submit'])) {
$userName = $_POST['name'];
$userEmail = $_POST['email'];
$userMessage = $_POST['message'];
$emailSubject = 'New Message From My Website Visitor';
$emailBody = 'Visitor Name: ' . $userName . '\n\n' .
'Visitor Email: ' . $userEmail . '\n\n' .
'Message: ' . $userMessage . '\n\n';
$emailTo = 'james_ross#outlook.fr';
$headers = 'From: ' . $emailFrom . '\n\n';
mail($emailTo, $emailSubject, $emailBody, $headers);
header('Location: index.js/mailsent');
}
If I need to use another technique/language in place of the PHP, please advise me of s decent source to read up on it, Thank you,
action="contact.php" is a relative link and it looks like your frontend runs as xxx/index.js/, you have to set it to an absolute url like action="/contact.php" or action="xxx/contact.php" where xxx is the folder with your php script.
If you develop with react than you don't want to switch between server side and client side pages, just send your form with ajax and display the output in your react app.
Your PHP code has a security issue:
$emailFrom is not defined, if you have some old PHP configuration with register_globals than it is possible to insert own header content and f.e. send spam emails to any email addresses.
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 8 years ago.
Improve this question
My website has a form that fires every time the website is accessed. It's still in testing phases so I get over 100 BLANK emails a day just from refreshing the page (and yes, all of the inputs are required). The tricky part is that I have a jquery script included. The script fires when you hit the submit button: it then refreshes the page and scrolls down (using a hashtag) to below my form with a message that basically says "thanks for emailing me!"
My code is posted below, but what I need to know is why I keep getting these blank emails even when the input fields are required! I am still very very new to php and jquery.
<?php
$to = 'design#carolbarone.com' ;
$subject = $_POST['subject'] ;
$name = $_POST['name'] ;
$email = $_POST['email'] ;
$text = $_POST['message'] ;
$message = "From: $name \nEmail: $email \nMessage: $text \n";
$sent = mail($to, $subject, $message) ;
if($sent) {
echo "";
}else{
echo "";
}
?>
<form data-abide name="input" action="index.php#hashtag" method="Post" id="theForm">
<div class="row">
<div class="small-10">
<div class="row">
<div class="small-12 columns name-field">
<input type="text" name="name" required id="right-label" placeholder="Name">
<small class="error">Name is required.</small> </div>
</div>
<div class="row">
<div class="small-12 columns email-field">
<input type="email" name="email" required id="right-label" placeholder="E-mail Address">
<small class="error">An email address is required.</small> </div>
</div>
<div class="row">
<div class="small-12 columns">
<input type="text" name="subject" required id="right-label" placeholder="Subject">
<small class="error">A subject is required.</small>
</div>
</div>
<div class="row">
<div class="large-12 columns">
<textarea name="message" placeholder="Your Message Here" rows="4" required></textarea>
<small class="error">A message is required.</small> </div>
</div>
</div>
</div>
<br/>
<button type="submit" name="submit" value="submit">Submit</button>
<button type="reset">Reset</button>
</form>
<br/>
<div class="success_message">
<h3>Thank you for your message!</h3>
<p>Your email has been sent successfully and I appreciate you getting in touch with me. I will be sending a reply soon.</p>
</div>
<script>
$(document).ready(function() {
if(window.location.hash == '#hashtag') {
$('.success_message').show();
$("html, body").animate({ scrollTop: $('#theForm').offset().top }, 1000);
}
});</script>
You never bothered fencing off your code to check if a form submission was actually performed, so the code will fire EVERY time the page is loaded. You'd want something at least like:
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
... handle form ...
}
They're required on the browser side, but you have no server-side validation. Older browsers that don't respect HTML5's required attribute, bots, etc. will happily submit all day long.
At its simplest, just check that there's data in each field:
$to = 'design#carolbarone.com' ;
$subject = $_POST['subject'] ;
$name = $_POST['name'] ;
$email = $_POST['email'] ;
$text = $_POST['message'] ;
$message = "From: $name \nEmail: $email \nMessage: $text \n";
if($subject && $name && $email && $text) {
$sent = mail($to, $subject, $message) ;
...
You'd want to do more validation (like making sure $email is a valid format) but this'll at least prevent blank ones. Of note: your form is vulnerable to header injection. Using a proper library like SwiftMailer will make coding email easier as well as protecting you from malicious spambots somewhat.
As Marc B notes, by including the mailing code on the same page as the form, you're firing it whenever someone accesses that page. Typically, your POST handling should be in a different file/route.
I need make this form send me a email like a contact form:
Script code:
<script type="text/javascript">
$(document).ready(function(){
$("#contactLink").click(function(){
if ($("#contactForm").is(":hidden")){
$("#contactForm").slideDown("slow");
}
else{
$("#contactForm").slideUp("slow");
}
});
});
function closeForm(){
$("#messageSent").show("slow");
setTimeout('$("#messageSent").hide();$("#contactForm").slideUp("slow")', 2000);
}
</script>
HTML CODE:
<div class="box">
<div id="contactFormContainer">
<div id="contactForm">
<fieldset>
<label for="Name">Nome: </label>
<input id="name" type="text" />
<label for="Telefone">Telefone Fixo: </label>
<input type="text" id="phone" maxlength="15" onkeypress="Mascara(this);" />
<label for="Message">Assunto:</label>
<textarea id="Message" rows="3" cols="20"></textarea>
<input id="sendMail" type="submit" name="submit" onclick="closeForm()" />
<span id="messageSent">Sua solicitação foi enviada com sucesso, por favor, aguarde...</span>
</fieldset>
</div>
<div id="contactLink"></div>
</div>
When click and close the form i need send me a email with the content of form, how to?
Some idea? thanks!
Firstly i can't see the form tags in your code. According to me you're doing this wrong and i'm sure many of our friends on stack will agree too.
Your question suggests that you basically want to receive an email with the data submitted through the form. Why don't you try the below method.
HTML
<form action="mail.php" method="POST">
<input type="text" name="fname"></input>
<input type="text" name="lname"></input>
<button>SUBMIT</button>
</form>
PHP
<?php
$firstname = $_POST['fname'];
$lastname = $_POST['lname'];
$to = "someone#example.com";
$subject = "Hello World";
$message = "Firstname: $firstname \n\n Lastname: $lastname";
$from = "sender#example.com";
$headers = "From:" . $from;
mail($to,$subject,$message,$headers);
echo "Mail Sent.";
?>
The above example is the most simplest method of sending an email. You can go advance by adding more header information and graphically formatting the email.
Go through these tutorials if you get confused.
http://www.w3schools.com/php/php_mail.asp
http://www.phpeasystep.com/phptu/8.html
And since you mentioned that you want to perform the task via javascript you can try submitting the form via ajax, refer the below tutorials
http://teachingyou.net/php/simple-php-contact-form-using-ajax/
http://www.sitepoint.com/forums/showthread.php?1055068-Send-PHP-email-using-jQuery-AJAX
Since you've tagged the question php, have a look at php's mail function. http://php.net/manual/en/function.mail.php
$to = 'you#domain.com';
$subject = 'Contact Form';
$message = '...' //concatenate the $_POST (or $_GET) variables to create this message
mail($to, $subject, wordwrap($message, 70, "\r\n");
This function requires that your server has a properly configured to send mail - see the php documentation for requirements: http://www.php.net/manual/en/mail.requirements.php
I've taken a few scripts from elsewhere on the Stack to create a contact form that emails me when the user submits.
HTML:
<form onsubmit="return getContent()">
<fieldset>
<input name="name" value="NAME" style="max-width:15%" type="text"/>
<input name="email" value="EMAIL" style="max-width: 30%" type="text"/>
<div id="message" contenteditable="true" name="message" value="expanding textarea">HELLO</div>
<textarea id="my-textarea" value="MESSAGE" style="display:none"></textarea>
<input type="submit" style="margin-right:0" value="Submit" />
</fieldset>
</form>
SCRIPTS:
function getContent(){
document.getElementById("my-textarea").value = document.getElementById("message").innerHTML;
}
$('form').submit( function() {
$.ajax({
type: "POST",
url: "email.php",
data: $(this).serialize(),
success: function() {
// Update page with success message
}
});
return false;
});
PHP:
<?php
$recipient = "my.email#whatever.com"; //recipient
$Name = ($_POST['name']); //senders name
$email = ($_POST['email']); //senders e-mail adress
$mail_body = ($_POST['message']); //mail body
$header = "From: ". $Name . " <" . $email . ">\r\n"; //optional headerfields
mail($recipient, $subject, $mail_body, $header); //mail command :)
?>
The script SHOULD get the content entered in the contenteditable div and pass it through to the hidden textarea, then submit to my email. However, it's currently only passing through the "name" and "email" fields and leaving the body of the email blank.
What have I missed here?
EDIT: Made a small error in the code hidden textarea above, value="MESSAGE" not "SUBJECT". Still, code not working.
Contenteditable content doesn't get passed through the form when submitted.
But, it looks like you're using some JS to get the content of the editable content div and put it into the textarea with a name of "subject".
Therefore, it will be accessible through $_POST['subject'] only.
Also, you're doing an onsubmit="" in the html and a on submit in the JS file. I don't think both will work, you'd be better combining the two (i.e. just use the JS file).
It also won't work without JS enabled, which I'd say is a bigger problem.