I'm creating a mobile app using onsen-ui framework and phonegap. I want to add an In-App "contact us" form, where a user can submit a form and on successful submission the form will be sent to email#domain.com.
In index.html I added
<script type="text/ons-template" id="contact.html">
<ons-navigator title="Navigator" var="sNavigator">
<ons-page id="page-contact">
<ons-toolbar>
<div class="left">
<ons-toolbar-button onclick="setHome();">
<ons-icon icon="fa-chevron-left"></ons-icon>
</ons-toolbar-button>
</div>
<div class="center white">
<span id="search-text" class="trn" data-trn-key="contact">Contact Us</span>
</div>
</ons-toolbar>
<div class="home-header">
<img src="css/images/banner.png" alt="" title="">
<p class="center trn" data-trn-key="contact">We respond to messages in the order received</p>
</div>
<form id="frm-contact" class="frm-contact" method="post">
<div class="wrapper">
<div class="field-wrapper">
<input type="text" name="first_name" class="first_name text-input text-input--underbar has_validation"
placeholder="First Name" value="" data-validation="required" data-validation-error-msg="this field is mandatory!" >
</div>
<div class="field-wrapper">
<input type="text" name="last_name" class="last_name text-input text-input--underbar has_validation"
placeholder="Last Name" value="" data-validation="required" data-validation-error-msg="this field is mandatory!" >
</div>
<div class="field-wrapper">
<input type="number" name="contact_phone" class="contact_phone text-input text-input--underbar has_validation"
placeholder="Mobile Phone" value="" data-validation="required" data-validation-error-msg="this field is mandatory!" >
</div>
<div class="field-wrapper">
<input type="email" name="email_address" class="email_address text-input text-input--underbar has_validation"
placeholder="Email address" value="" data-validation="email" data-validation-error-msg="this field is mandatory!" >
</div>
<div class="field-wrapper">
<input type="text" name="subject" class="subject text-input text-input--underbar has_validation"
placeholder="Subject" value="" data-validation="required" data-validation-error-msg="this field is mandatory!" >
</div>
<div class="field-wrapper">
<textarea style="width:100%;height:80px" name="message" class="message text-input text-input--underbar has_validation"
placeholder="Your Message" value="" data-validation="required" data-validation-error-msg="this field is mandatory!" ></textarea>
</div>
<p class="small-font-dim trn" data-trn-key="create_account_terms">
Please note all fields are mandatory, you should fill in all before submission.</p>
</div>
<button class="button green-btn button--large trn" onclick="contact();" data-trn-key="contact" >
Submit Now!
<div class="search-btn"><ons-icon icon="fa-chevron-right"></ons-icon></div>
</button>
</form>
</ons-page>
</ons-navigator>
</script>
Then I'm validating the form in the .js file and calling the API function
case "page-contact":
translatePage();
translateValidationForm();
$(".full_name").attr("placeholder", getTrans("Full Name",'full_name') );
$(".last_name").attr("placeholder", getTrans('Last Name','last_name') );
$(".contact_phone").attr("placeholder", getTrans('Mobile Phone','contact_phone') );
$(".email_address").attr("placeholder", getTrans('Email address','email_address') );
$(".subject").attr("placeholder", getTrans('Subject','subject') );
$(".message").attr("placeholder", getTrans('Your Message','message') );
break;
Here I'm doing the validation and calling the API from the webserver:
function contact()
{
$.validate({
form : '#frm-contact',
borderColorOnError:"#FF0000",
onError : function() {
},
onSuccess : function() {
var params = $( "#frm-contact").serialize();
params+="&device_id="+ getStorage("device_id");
callAjax("contact",params);
return false;
}
});
}
At the webserver end the PHP code includes
public function actionContact($to='',$from='',$subject='',$body='')
{
$from1=Yii::app()->functions->getOptionAdmin('global_admin_sender_email');
if (!empty($from1)){
$from=$from1;
}
$email_provider=Yii::app()->functions->getOptionAdmin('email_provider');
if ( $email_provider=="smtp"){
$smtp_host=Yii::app()->functions->getOptionAdmin('smtp_host');
$smtp_port=Yii::app()->functions->getOptionAdmin('smtp_port');
$smtp_username=Yii::app()->functions->getOptionAdmin('smtp_username');
$smtp_password=Yii::app()->functions->getOptionAdmin('smtp_password');
$mail=Yii::app()->Smtpmail;
Yii::app()->Smtpmail->Host=$smtp_host;
Yii::app()->Smtpmail->Username=$smtp_username;
Yii::app()->Smtpmail->Password=$smtp_password;
Yii::app()->Smtpmail->Port=$smtp_port;
$mail->SetFrom($from, '');
$mail->Subject = $subject;
$mail->MsgHTML($body);
$mail->AddAddress($to, "");
if(!$mail->Send()) {
//echo "Mailer Error: " . $mail->ErrorInfo;
return false;
}else {
//echo "Message sent!";
return true;
}
} elseif ( $email_provider=="mandrill"){
$api_key=Yii::app()->functions->getOptionAdmin('mandrill_api_key');
try {
require_once 'mandrillapp/Mandrill.php';
$mandrill = new Mandrill($api_key);
$message = array(
'html' => $body,
'text' => '',
'subject' => $subject,
'from_email' => $from,
//'from_name' => 'Example Name',
'to' => array(
array(
'email' => $to,
//'name' => 'Recipient Name',
'type' => 'to'
)
)
);
$async = false;
$ip_pool = '';
$send_at = '';
$result = $mandrill->messages->send($message, $async, $ip_pool, $send_at);
//dump($result);
if (is_array($result) && count($result)>=1){
if ($result[0]['status']=="sent"){
return true;
}
}
} catch(Mandrill_Error $e) {
//echo 'A mandrill error occurred: ' . get_class($e) . ' - ' . $e->getMessage();
}
return false;
}
$body = $_POST['first_name']. ' ' .$_POST['last_name']. ' ' .$_POST['contact_phone']. ' ' .$_POST['message'];
$to = 'info#domain.com';
$from = $_POST['email_address'];
$headers = "From: $from\r\n";
$headers .= "Content-type: text/html; charset=UTF-8\r\n";
$subject = $_POST['subject'];
$message =<<<EOF
$body
EOF;
if (!empty($to)) {
if (#mail($to, $subject, $message, $headers)){
return true;
}
}
return false;
}
The form is sending the email, however if there is no/null data I can't get the information submitted.
Please advise, thank you.
Based on what you posted, there was an error regarding the device ID. Specifically, the function getStorage was undefined. The code posted below works fine and was able to send all the fields via post to my test PHP page and send an email. Granted, I didn't use a complex PHP processor as you have, but it works!
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<meta name="apple-mobile-web-app-capable" content="yes" />
<meta name="mobile-web-app-capable" content="yes" />
<meta http-equiv="Content-Security-Policy" content="default-src * data:; style-src * 'unsafe-inline'; script-src * 'unsafe-inline' 'unsafe-eval'">
<link rel="shortcut icon" href="favicon.ico" type="image/x-icon" />
<link href='https://fonts.googleapis.com/css?family=Roboto:400,300italic,300,400italic,500,700,700italic,500italic' rel='stylesheet' type='text/css'>
<title>Onsen UI 2.0 Quickstart</title>
<script src="components/loader.js"></script>
<script src="lib/onsenui/js/onsenui.js"></script>
<link rel="stylesheet" href="lib/onsenui/css/onsenui.css" type="text/css" media="all" />
<link rel="stylesheet" href="lib/onsenui/css/onsen-css-components.css" type="text/css" media="all" />
<script src="https://code.jquery.com/jquery-1.10.2.js"></script>
<script>
function contact()
{
var params = $( "#frm-contact").serialize();
console.log(params);
}
</script>
</head>
<body>
<ons-page id="page-contact">
<ons-toolbar>
<div class="left">
<ons-toolbar-button onclick="setHome();">
<ons-icon icon="fa-chevron-left"></ons-icon>
</ons-toolbar-button>
</div>
<div class="center white">
<span id="search-text" class="trn" data-trn-key="contact">Contact Us</span>
</div>
</ons-toolbar>
<div class="home-header">
<img src="css/images/banner.png" alt="" title="">
<p class="center trn" data-trn-key="contact">We respond to messages in the order received</p>
</div>
<form id="frm-contact" class="frm-contact" method="post">
<div class="wrapper">
<div class="field-wrapper">
<input type="text" name="first_name" class="first_name text-input text-input--underbar has_validation"
placeholder="First Name" value="" data-validation="required" data-validation-error-msg="this field is mandatory!" >
</div>
<div class="field-wrapper">
<input type="text" name="last_name" class="last_name text-input text-input--underbar has_validation"
placeholder="Last Name" value="" data-validation="required" data-validation-error-msg="this field is mandatory!" >
</div>
<div class="field-wrapper">
<input type="number" name="contact_phone" class="contact_phone text-input text-input--underbar has_validation"
placeholder="Mobile Phone" value="" data-validation="required" data-validation-error-msg="this field is mandatory!" >
</div>
<div class="field-wrapper">
<input type="email" name="email_address" class="email_address text-input text-input--underbar has_validation"
placeholder="Email address" value="" data-validation="email" data-validation-error-msg="this field is mandatory!" >
</div>
<div class="field-wrapper">
<input type="text" name="subject" class="subject text-input text-input--underbar has_validation"
placeholder="Subject" value="" data-validation="required" data-validation-error-msg="this field is mandatory!" >
</div>
<div class="field-wrapper">
<textarea style="width:100%;height:80px" name="message" class="message text-input text-input--underbar has_validation"
placeholder="Your Message" value="" data-validation="required" data-validation-error-msg="this field is mandatory!" ></textarea>
</div>
<p class="small-font-dim trn" data-trn-key="create_account_terms">
Please note all fields are mandatory, you should fill in all before submission.</p>
</div>
<button class="button green-btn button--large trn" onclick="contact();" data-trn-key="contact" >
Submit Now!
<div class="search-btn"><ons-icon icon="fa-chevron-right"></ons-icon></div>
</button>
</form>
</ons-page>
</body>
</html>
PHP:
<?php
$to = 'test#test.com';
$from = $_REQUEST['email_address'];
$message = $_REQUEST['message'];
$subject = $_REQUEST['subject'];
$header = "From: <".$email_address.">" ."\r\n";
$send = #mail($to, $subject, $message, $header);
if(!$send){
die();
}
?>
Also, do note that I didn't send your other fields [first_name, last_name, contact_phone] but they can be added anywhere. Lastly, this is by no means a secure method of sending mail, but something thrown together to prove that Onsen does not interfere with the sending of mail via an HTML form with jQuery.
Edit: Although this is branching from the actual question, based on your comments, I would highly recommend reading some of these:
https://codereview.stackexchange.com/questions/19365/is-this-a-secure-and-best-practice-php-mail-function
Secure php email script
What is the best way to send a secure email in PHP
For GOOGLERS:
Thanks to #munsterlander I was able to resolve the issue by replacing the $_POST to $_GET which helped doing the whole process in the way needed.
$body = $_GET['first_name']. ' ' .$_GET['last_name']. ' ' .$_GET['contact_phone']. ' ' .$_GET['message'];
$to = 'info#domain.com';
$from = $_GET['email_address'];
$headers = "From: $from\r\n";
$headers .= "Content-type: text/html; charset=UTF-8\r\n";
$subject = $_GET['subject'];
$message =<<<EOF
$body
EOF;
Related
I have a contact form on a website, and I am trying to submit the form using Google recaptcha v2, (select the boxes which have a certain image in them). At the moment, the form successfully sends and is received exactly as I want it to; however, I want to create a 'success' alert using Bootstrap, but for some reason this is not working.
If you take a look at the last part of my PHP file I have the following code snippet:
if($responseKeys["success"]) {
mail($to,$email_subject,$email_body,$headers);
} else {
echo '<h2>This has been unsuccessful according to our security checks</h2>';
}
And the 'mail' command seems to work. But anything else I try to put in there, for example
echo '<h2>success!</h2>'
for example, it doesn't get rendered. Ideally, upon a success submit I would like the following to take place:
The form to refresh to blank
A success alert using Bootstrap show at the top of the page
But I am having trouble implementing these.
Here is the entire PHP file:
<?php
$Fname = $_POST['Fname'];
$Lname = $_POST['Lname'];
$email = $_POST['email'];
$number = $_POST['number'];
$company = $_POST['company'];
$message = $_POST['message'];
$email_from = "Your website";
$email_subject = "You have a new submission form from Your Website";
$email_body = "First Name: $Fname.\n".
"Last Name: $Lname.\n".
"Email Address: $email.\n".
"Telephone Number: $number.\n".
"Company Name: $company.\n".
"Message: $message.\n";
$to = "hello#yourwebsite.co.uk";
$headers = "From: $email_from \r\n";
$headers .= "Reply-To: $email \r\n";
$captcha;
if(isset($_POST['email'])){
$email=$_POST['email'];
}
if(isset($_POST['message'])){
$message=$_POST['message'];
}
if(isset($_POST['g-recaptcha-response'])){
$captcha=$_POST['g-recaptcha-response'];
}
if(!$captcha){
echo '<h2>Please check the "I am not a robot" checkbox"</h2>';
exit;
}
$secretKey = 'somesecretlettersandnumbers';
$ip = $_SERVER['REMOTE_ADDR'];
// post request to the server
$url = 'https://www.google.com/recaptcha/api/siteverify?secret=' . urlencode($secretKey) . '&response=' . urlencode($captcha);
$response = file_get_contents($url);
$responseKeys = json_decode($response, true);
// should return JSON with success as true
if($responseKeys["success"]) {
mail($to,$email_subject,$email_body,$headers);
} else {
echo '<h2>This has been unsuccessful according to our security checks</h2>';
}
?>
And here is the HTML form:
<form action="contact.php" id="contact-form" method="POST" role="form">
<div class="row">
<div class="col">
<div class="form-group">
<label for="form_name">First Name*</label>
<input id="form_name" type="text" class="form-control" name="Fname" placeholder="David" required data-error='Please fill in your first name'>
<div class="help-block with-errors"></div>
</div>
</div>
<div class="col">
<div class="form-group">
<label for="form_lastname">Last name*</label>
<input id="form_lastname" type="text" class="form-control" name="Lname" placeholder="Beckham" required data-error="Please fill in your last name">
<div class="help-block with-errors"></div>
</div>
</div>
</div>
<div class="row">
<div class="col">
<div class="form-group">
<label for="form_email">Email address*</label>
<input id="form_email" type="email" class="form-control" name="email" placeholder="becks#example.com" required data-error="Please provide your email address">
<div class="help-block with-errors"></div>
</div>
</div>
<div class="col">
<div class="form-group">
<label for="form_number">Contact number*</label>
<input id="form_number" type="number" class="form-control" name="number" placeholder="01234567890" required data-error="Please provide a contact number">
<div class="help-block with-errors"></div>
</div>
</div>
</div>
<div class="row">
<div class="col">
<div class="form-group">
<label for="form_company">Your company name</label>
<input id="form_company" type="text" class="form-control" name="company" placeholder="Ex-footballers r us">
</div>
</div>
</div>
<div class="row">
<div class="col">
<div class="form-group">
<label for="form_message">Your message*</label>
<textarea id="form_message" class="form-control" name="message" cols="30" rows="10" placeholder="Here's my message" required></textarea>
<div class="help-block with-errors"></div>
</div>
</div>
</div>
<div class="row">
<div class="col">
<div class="g-recaptcha" data-sitekey="datasitekeynumbersandletters"></div>
</div>
</div>
<div class="row">
<div class="col">
<input type="submit" class="btn btn-outline-brand btn-block" name="submit" value="Send enquiry">
</div>
</div>
</form>
I have tried following this tutorial:
Bootstrap success alert upon form submition via javascript
Edited to add the only JS I have for this file:
<script src="https://www.google.com/recaptcha/api.js" async defer></script>
without success.
Thank you in advance
I have created a form based on the bootstrapious.com contact form tutorial. In my case I have changed it to populate a mysql database. Filling out the form and submitting it does get the information correctly in the database, but does not return a 'success' message or reset the form. I think the problem is in my javascript but am not sure. I would appreciate any help. Thanks
Here is my html
<!DOCTYPE html>
<html>
<head>
<title>Family Member</title>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" rel="stylesheet">
<link href='https://fonts.googleapis.com/css?family=Lato:300,400,700' rel='stylesheet' type='text/css'>
<link href='custom.css' rel='stylesheet' type='text/css'>
</head>
<body>
<div class="container">
<div class="row">
<div class="col-lg-8 col-lg-offset-2">
<h1>Family Member Form</h1>
<p class="lead">Please enter your information on the form below</p>
<form id="familyMember-form" method="post" action="familyMember.php" role="form">
<div class="messages"></div>
<div class="controls">
<div class="row">
<div class="col-md-6">
<div class="form-group">
<label for="form_firstname">Firstname *</label>
<input id="form_firstname" type="text" name="firstName" class="form-control" placeholder="Please enter your firstname *" required="required" data-error="Firstname is required.">
<div class="help-block with-errors"></div>
</div>
</div>
<div class="col-md-6">
<div class="form-group">
<label for="form_lastname">Lastname *</label>
<input id="form_lastname" type="text" name="lastName" class="form-control" placeholder="Please enter your lastname *" required="required" data-error="Lastname is required.">
<div class="help-block with-errors"></div>
</div>
</div>
</div>
<div class="row">
<div class="col-md-6">
<div class="form-group">
<label for="form_email">Email *</label>
<input id="form_email" type="email" name="email" class="form-control" placeholder="Please enter your email *" required="required" data-error="Valid email is required.">
<div class="help-block with-errors"></div>
</div>
</div>
<div class="col-md-6">
<div class="form-group">
<label for="form_cellPhone">Cell Phone</label>
<input id="form_cellPhone" type="tel" name="cellPhone" class="form-control" placeholder="Please enter your cell phone number">
<div class="help-block with-errors"></div>
</div>
</div>
</div>
<div class="row">
<div class="col-md-6">
<div class="form-group">
<label for="form_password">Password*</label>
<input id="form_password" type="password" name="password" class="form-control" placeholder="Please enter your password*">
<div class="help-block with-errors"></div>
</div>
</div>
<div class="col-md-6">
<div class="form-group">
<label for="form_passwordConfirmation">Confirm Password*</label>
<input id="form_passwordConfirmation" type="password" name="passwordConfirmation" class="form-control" placeholder="Please confirm your password*">
<div class="help-block with-errors"></div>
</div>
</div>
</div>
<div class="row">
<div class="col-md-12">
<div class="form-group">
<label for="form_familyCode">Family Code *</label>
<input id="form_familyCode" name="familyCode" class="form-control" placeholder="Please Enter Family Code *" rows="4" required="required" data-error="Please,leave us a message.">
<div class="help-block with-errors"></div>
</div>
</div>
</div>
<div class="row">
<div class="col-md-12">
<input type="submit" class="btn btn-primary" value="Submit">
</div>
</div>
<div class="row">
<div class="col-md-12">
<p></p>
<p class="text-muted"><strong>*</strong> These fields are required.</p>
</div>
</div>
</div>
</form>
</div><!-- /.8 -->
</div> <!-- /.row-->
</div> <!-- /.container-->
<script src="https://code.jquery.com/jquery-1.12.0.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>
<script src="validator.js"></script>
<script src="familyMember.js"></script>
</body>
</html>
Here is my php
$okMessage = 'Family member has successfully added.';
$errorMessage = 'there was an error';
try
{
$pdo = new PDO('mysql:host=localhost; dbname=mydb', "user", "password");
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$pdo->exec('SET NAMES "utf8"');
}
catch (PDOException $e)
{
$output = 'Unable to connect to the database server:' . $e->getMessage();
include 'output.html.php';
exit();
}
//$output = 'Database connection established.';
//include 'output.html.php';
$firstName = $_POST['firstName'];
//echo $firstName;
//echo '<br>';
$lastName = $_POST['lastName'];
//echo $lastName;
//echo '<br>';
$email = $_POST['email'];
//echo $email;
//echo '<br>';
$cellPhone = $_POST['cellPhone'];
//echo $cellPhone;
//echo '<br>';
$password = $_POST['password'];
//echo $password;
//echo '<br>';
$familyCode = $_POST['familyCode'];
//echo $familyCode;
//echo '<br>';
try{
$sql = 'INSERT INTO familyMembers(FirstName, LastName, Email, Password, cell_phone, familyCode)
Values(:FirstName, :LastName, :Email, :Password, :cell_phone, :familyCode)';
$statement = $pdo -> prepare($sql);
$statement -> execute(array(':FirstName' => $firstName, ':LastName' =>$lastName, ':Email'=> $email, ':Password'=> $password, ':cell_phone' => $cellPhone, ':familyCode' => $familyCode));
$responseArray = array('type' => 'success', 'message' => $okMessage);
}
catch (\Exception $e){
$responseArray = array('type' => 'danger', 'message' => $errorMessage);
}
if (!empty($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest') {
$encoded = json_encode($responseArray);
header('Content-Type: application/json');
echo $encoded;
}
else {
echo $responseArray['message'];
}
Here is my javascript
$(function () {
$('#familyMember-form').validator();
$('#familyMember-form').on('submit', function (e) {
if (!e.isDefaultPrevented()) {
var url = "familyMember.php";
alert(url);
$.ajax({
type: "POST",
url: url,
data: $(this).serialize(),
success: function (data)
{
alert(url);
alert(data);
var messageAlert = 'alert-' + data.type;
var messageText = data.message;
alert(messageAlert);
alert(messageText);
var alertBox = '<div class="alert ' + messageAlert + ' alert-dismissable"><button type="button" class="close" data-dismiss="alert" aria-hidden="true">×</button>' + messageText + '</div>';
if (messageAlert && messageText) {
$('#familyMember-form').find('.messages').html(alertBox);
$('#familyMember-form')[0].reset();
}
}
});
return false;
}
});
});
I am not able to edit this 'contact us' form code work and deliver messages to my mail-box.
Say I wanted to get messages delivered to my email: doherty#noob.com, how do I edit this code do the task?
<div class="conatct-form">
<ul class="form">
<li>
<input type="text" class="text" value="Name*" onfocus="this.value = '';" onblur="if (this.value == '') {this.value = 'Name*';}" >
</li>
<li>
<input type="text" class="text" value="Email*" onfocus="this.value = '';" onblur="if (this.value == '') {this.value = 'Email*';}" >
</li>
<li>
<textarea value="Message*:" onfocus="this.value = '';" onblur="if (this.value == '') {this.value = 'Your Message*';}">Message*</textarea>
</li>
<div class="sub-button">
<input type="submit" value="SEND">
</div>
</ul>
</div>
I've optimized your code and added some PHP code
PHP code
<?php
$name = $_POST['name'];
$email = $_POST['email'];
$message = $_POST['message'];
if (isset($name, $email, $message)) {
// Insert into database
$query = mysql_query("INSERT INTO contacts ...");
if ($query) {
// send email using phpmailer, sendmail, ...
mail($mail, 'Subject', $message, '...');
}
}
?>
HTML
<form id="contact-form" method="post">
<ul>
<li>
<!--
Substituting the code below
<input type="text"
value="Name *"
onfocus="this.value=''"
onblur="if (this.value == '') {this.value = 'Name *'}" />
use the placeholder attribute instead
-->
<input type="text" name="name" placeholder="Name *" />
</li>
<li>
<input type="text" name="email" placeholder="Email *" />
</li>
<li>
<textarea name="message" placeholder="Message *"></textarea>
</li>
<li>
<input type="submit" value="Send" />
</li>
</ul>
</form>
You need to wrap your HTML inputs in a element in order for proper form to work.
Thus, you'll need the following tag:
<form action='url_to_submit_to' method='POST' enctype='application/x-www-form-urlencoded'>
<!-- Rest of your code here -->
</form>
See the Mozilla documentation for more details on the format and arguments of the <form> tag:
https://developer.mozilla.org/en-US/docs/Web/HTML/Element/form
Here submit is not happening because the content is not wrapped inside a form tag.
All the content should be wrapped inside tag which has action attribute to some php/java file which validate the data passed by user and commits to database.
Please check form tag on mdn for more information.
rather than you using
if (isset($name, $email, $message)) {...}
there HTML5 'required' will be better in your tags. e.g
Also, you submit type needs to have a name. the name will be used to process your form.
contact.php page. the form below processes itself since the method is its name, contact.php.
<form id="contact-form" method="post" action="contact.php" >
<input type="text" name="name" placeholder="Name" />
<input type="text" name="subject" placeholder="Subject *" />
<input type="text" name="email" placeholder="Email *" />
<textarea name="message" placeholder="Message *"></textarea>
<input type="submit" value="Send" name="send"/>
</form>
<?php
if (isset($_POST['send'])) {
$to = "youremail#something.com";
$subject = $_POST['subject'];
$message = $_POST['message'];
$from = $_POST['email'];
$headers = "From: $from $name";
$sent = mail($to,$subject,$message,$headers);
if ($sent) {
echo "<p style = 'color: #00ff00;'>Message was sent.</p>";
}
else {
echo "<p style = 'color: #ff0000;'>Message was not sent.</p>";
}
}
?>
I have an HTML page with a form that posts to a sendmail.php file but when I click submit I get sent to the blank php page with the words "Email sent!".
I would like to click Submit and then instead of going into a separate page, it stays on the same page and the submit button changes color and reads "Message Sent". How do I do this?
HTML Code:
<form action="sendmail.php" method="POST" enctype="multipart/form-data">
<input type="hidden" name="action" value="submit">
<div class="row half">
<div class="6u">
<input type="text" name="name" placeholder="Name" />
</div>
<div class="6u">
<input type="text" name="number" placeholder="Number" />
</div>
</div>
<div class="row half">
<div class="12u">
<textarea name="message" placeholder="Message" rows="6"></textarea>
</div>
</div>
<div class="row">
<div class="12u">
<ul class="actions">
<li>
<input type="submit" value="Send Message" />
</li>
</ul>
</div>
</div>
</form>
PHP Code:
<?php
{
$name=$_REQUEST['name'];
$number=$_REQUEST['number'];
$message=$_REQUEST['message'];
$headers = "From: $name<form#site.com>\r\n";
$headers .= "MIME-Version: 1.0\r\n";
$headers .= "Content-Type: text/html; charset=ISO-8859-1\r\n";
if (($name=="")||($number=="")||($message==""))
{
echo "All fields are required, please fill the form again.";
}
else{
$subject="Website Contact Form";
mail("me#gmail.com", $subject, "<font size='+1'>Hello, this is a message from your website's contact form.<br><br>This message was sent by <b>".$name.".</b><br>The phone number they provided was <b>".$number.".</b><br><br>Their message is as follows:<br><b>".$message."</b></font>", $headers);
echo "Email sent!";
}
}
?>
Thanks for the help!
get jquery library in your head section
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
then you want to write ajax method
sample:
$(document).ready(function(){
$('form').submit(function(e){
var arr;
e.preventDefault();
$.ajax({
type: 'POST',
url: "sendmail.php",
//this specifies the data to be sent to server through php you should modify accordingly
data:{name:$('input[name="name"]').val()},
async:true,
success: function(result){
//do something with the result if request is successful
}
});
});
});
Change action in form tag.
<form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="POST" enctype="multipart/form-data">
<input type="hidden" name="action" value="submit">
<div class="row half">
<div class="6u">
<input type="text" name="name" placeholder="Name" />
</div>
<div class="6u">
<input type="text" name="number" placeholder="Number" />
</div>
</div>
<div class="row half">
<div class="12u">
<textarea name="message" placeholder="Message" rows="6"></textarea>
</div>
</div>
<div class="row">
<div class="12u">
<ul class="actions">
<li>
<input type="submit" value="Send Message" />
</li>
</ul>
</div>
</div>
</form>
<?php
if(isset($_REQUEST['name']) && ($_REQUEST['name']!="")|| isset($_REQUEST['number']) && ($_REQUEST['number']!="")|| isset($_REQUEST['message']) && ($_REQUEST['message']!=""))
{
$name=$_REQUEST['name'];
$number=$_REQUEST['number'];
$message=$_REQUEST['message'];
$headers = "From: $name<form#site.com>\r\n";
$headers .= "MIME-Version: 1.0\r\n";
$headers .= "Content-Type: text/html; charset=ISO-8859-1\r\n";
if (($name=="")||($number=="")||($message==""))
{
echo "All fields are required, please fill the form again.";
}
else{
$subject="Website Contact Form";
mail("me#gmail.com", $subject, "<font size='+1'>Hello, this is a message from your website's contact form.<br><br>This message was sent by <b>".$name.".</b><br>The phone number they provided was <b>".$number.".</b><br><br>Their message is as follows:<br><b>".$message."</b></font>", $headers);
echo "Email sent!";
}
}
else{
print_r(22);exit;
}
?>
so what you need is jquery.form, it can help you submit the form by ajax.
You can use JQuery for this purpose.
<form id="noRedirection" enctype="multipart/form-data" method="POST">
<div class="row half">
<div class="6u">
<input type="text" name="name" placeholder="Name" />
</div>
<div class="6u">
<input type="text" name="number" placeholder="Number" />
</div>
</div>
<div class="row half">
<div class="12u">
<textarea name="message" placeholder="Message" rows="6"></textarea>
</div>
</div>
<div class="row">
<div class="12u">
<ul class="actions">
<li>
<input id="submit" type="submit" value="Send Message" />
</li>
</ul>
</div>
</div>
</form>
<script>
$('#noRedirection').submit(function() {
var post_data = $('#noRedirection').serialize();
$.post('sendMail.php', post_data, function(data) {
$("#submit").text('Message Sent').css("color","red");
});
});
</script>
All you need to learn is how to make ajax calls.
Refer this link from stackoverflow itself . Here you can see how all variables and of data regarding mail is sent through ajax call to another page for mailing.
Click Here
I hope this will help you. you no need to give an action. see my example it will stay same page but request will go another page. just copy and paste this code and don't run on localhost because email is not send on localhost:
<script src="http://code.jquery.com/jquery-1.9.1.js"></script>
<script>
$(function () {
$('form').on('submit', function (e) {
e.preventDefault();
$.ajax({
type: 'post',
url: 'sendmail.php',
data: $('form').serialize(),
success: function (d) {
alert(d);
}
});
});
});
</script>
<form action="" method="POST" enctype="multipart/form-data">
<input type="hidden" name="action" value="submit">
<div class="row half">
<div class="6u">
<input type="text" name="name" placeholder="Name" />
</div>
<div class="6u">
<input type="text" name="email" placeholder="Email" />
</div>
<div class="6u">
<input type="text" name="number" placeholder="Number" />
</div>
</div>
<div class="row half">
<div class="12u">
<textarea name="message" placeholder="Message" rows="6"></textarea>
</div>
</div>
<div class="row">
<div class="12u">
<ul class="actions">
<li>
<input type="submit" name="send" value="Send Message" />
</li>
</ul>
</div>
</div>
</form>
make new page of sendmail.php and paste this code in that file:
echo $name = $_POST['name'];
echo $number = $_POST['number'];
echo $email = $_POST['email'];
echo $message = $_POST['message'];
$headers = "From: $name<form#site.com>\r\n";
$headers .= "MIME-Version: 1.0\r\n";
$headers .= "Content-Type: text/html; charset=ISO-8859-1\r\n";
if (($name=="")||($number=="")||($message=="") || ($email=="")) {
echo "All fields are required, please fill again.";
} else {
$subject="Website Contact Form";
mail($email, $subject, "<font size='+1'>Hello, this is a message from your website's contact form.<br><br>This message was sent by <b>".$name.".</b><br>The phone number they provided was <b>".$number.".</b><br><br>Their message is as follows:<br><b>".$message."</b></font>", $headers);
echo "Email sent!";
}
<form action="sendmail.php" method="POST" enctype="multipart/form-data">
<input type="hidden" name="action" value="submit">
You're already using php, so there's no reason at all to use jquery as well, just take the code from your sendmail.php file and put it in the top of this. Using javascript for core page functionality used to be considered bad practice, it's certainly annoying to users with javascript blockers running, makes the pages very hard to use, stackoverflow does that too.
Rather than submit to the other file, just delete the 'action="sendmail.php"' which will then make the page submit to itself, or put in the actual url of the page if it's got a static url that you know. Or use:
action="<?php echo $_SERVER['REQUEST_URI'];?>"
which sets it to whatever the uri of the page is, that's useful for things that generate the pages from query string data.
Then you check to see the following (how did stackoverflow get so popular without having good code blocks?)
if ( isset($_POST['action']) ) {
set color to red or whatever...
and that's all.
Another which is also help you:
if(isset($_POST['name']) && ($_POST['name']!="")|| isset($_POST['number']) && ($_POST['number']!="")|| isset($_POST['message']) && ($_POST['message']!="")){
$name=$_POST['name'];
$number=$_POST['number'];
$message=$_POST['message'];
$headers = "From: $name<form#site.com>\r\n";
$headers .= "MIME-Version: 1.0\r\n";
$headers .= "Content-Type: text/html; charset=ISO-8859-1\r\n";
if (($name=="")||($number=="")||($message=="")) {
echo "All fields are required, please fill the form again.";
} else{
$subject="Website Contact Form";
$to = 'admin#gmail.com';
mail($to, $subject, "<font size='+1'>Hello, this is a message from your website's contact form.<br><br>This message was sent by <b>".$name.".</b><br>The phone number they provided was <b>".$number.".</b><br><br>Their message is as follows:<br><b>".$message."</b></font>", $headers);
echo "Email sent!";
}
}
<form action="" method="POST">
<input type="hidden" name="action" value="submit">
<div class="row half">
<div class="6u">
<input type="text" name="name" placeholder="Name" />
</div>
<div class="6u">
<input type="text" name="number" placeholder="Number" />
</div>
</div>
<div class="row half">
<div class="12u">
<textarea name="message" placeholder="Message" rows="6"></textarea>
</div>
</div>
<div class="row">
<div class="12u">
<ul class="actions">
<li>
<input type="submit" value="Send Message" />
</li>
</ul>
</div>
</div>
</form>
So I have the JavaScript code which validates the first name field, I am adding more validation once I have worked this out.
So basically if the field is not filled in, return false.
If it is return true and continue to email.php to send the email. Only problem is its not sending the email to the set address. I am confused as to where I have gone wrong.
The JavaScript is working when the field is empty, and when it has an input. Help.
PS: I have removed email address for privacy purposes.
JavaScript on contact.html:
<script>
function validateForm() {
if (document.forms['email'].fname.value == ""){
alert("First name must be filled out");
return false;
}
else{
alert("Thank you! Your message was recieved!");
return true;
}
};
</script>
Html form on contact.html
<form id="email" name="email" onsubmit="return validateForm(this)" action="email.php" method="post" >
<div id="form_fname">
<label for="fname"><img src="images/firstname.png" width="94" height="17" alt="first name" /></label>
<input type="text" name="fname" id="fname" />
</div>
<div id="form_lname">
<label for="lname"><img src="images/lastname.png" width="89" height="17" alt="last name" /></label>
<input type="text" name="lname" id="lname" />
</div>
<div id="form_email">
<label for="email"><img src="images/email.png" width="53" height="17" alt="email" /></label>
<input type="text" name="email" id="email" />
</div>
<div id="form_message">
<label for="Message"><img src="images/message.png" width="77" height="17" alt="message" /></label>
<textarea name="message" id="message" cols="45" rows="5"></textarea>
</div>
<div id="form_submit">
<input type="submit" name="submit" id="submit" value=""/>
</div>
</form>
Php in email.php
<?php
if(isset($_POST['email'])) {
// Email and subject.
$email_to = "emailaddress";
$email_subject = "Mint Makeup & Beauty Enquiry";
$fname = $_POST['fname']; // required
$lname = $_POST['lname']; // required
$message = $_POST['message']; // required
$email_from = $_POST['email']; // required
// create email content
$email_content = "From:"." ".$fname." ".$lname."\n"."Email:"." ".$email_from."\n"."Message:"." ".$message;
//mail
mail($email_to, $email_subject, $email_content);
}
//return to contact page after submit.
header("location:contact.html");
?>
In your form id="email" is conflicting with input id="email"
You can use HTML5 attributes for form validation (in HTML5 supported browsers)
http://www.the-art-of-web.com/html/html5-form-validation/#.UnDpBHMW3eU
Code
<?php
if(isset($_POST['submit'])) {
print_r($_POST);
die;
$email_to = "emailaddress";
$email_subject = "Mint Makeup & Beauty Enquiry";
$fname = $_POST['fname']; // required
$lname = $_POST['lname']; // required
$message = $_POST['message']; // required
$email_from = $_POST['email']; // required
// create email content
$email_content = "From:"." ".$fname." ".$lname."\n"."Email:"." ".$email_from."\n"."Message:"." ".$message;
mail($email_to, $email_subject, $email_content);
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
<script type="text/javascript">
function validateForm() {
var error = false;
var error_string = 'Please correct the following errors:\n\n';
if (document.getElementById('fname').value == ""){
error_string += "--> First name must be filled out.\n";
error = true;
}
if (document.getElementById('lname').value == ""){
error_string += "--> Last name must be filled out.\n";
error = true;
}
if (document.getElementById('email').value == ""){
error_string += "--> Email must be filled out.\n";
error = true;
}
if(error){
alert(error_string);
return false;
} else {
return true;
}
}
</script>
</head>
<body>
<form onsubmit="return validateForm(this)" action="" method="post" >
<div id="form_fname">
<label for="fname"><img src="images/firstname.png" width="94" height="17" alt="first name" /></label>
<input type="text" name="fname" id="fname" />
</div>
<div id="form_lname">
<label for="lname"><img src="images/lastname.png" width="89" height="17" alt="last name" /></label>
<input type="text" name="lname" id="lname" />
</div>
<div id="form_email">
<label for="email"><img src="images/email.png" width="53" height="17" alt="email" /></label>
<input type="text" name="email" id="email" />
</div>
<div id="form_message">
<label for="Message"><img src="images/message.png" width="77" height="17" alt="message" /></label>
<textarea name="message" id="message" cols="45" rows="5"></textarea>
</div>
<div id="form_submit">
<input type="submit" name="submit" id="submit" value="Submit" />
</div>
</form>
</body>
</html>
I just showed you how client side validation works and form is posting correctly.. You should always use server side validation..
Try
document.forms["email"]["fname"].value
instead
document.forms['email'].fname.value
Also you can get field this way:
document.getElementById('fname').value