I have Javascript/Ajax and PHP validation for my form. It's displays the errors if the form filled incorrectly, but it won't work and let me submit the form even if there is no errors. Basically ,when I click the submit button it stays at the same page and won't do anything.
In console I got the next error on submit: Failed to load file:///C:/Users/ilona/Desktop/BootstrapLandinPage/send.php: Cross origin requests are only supported for protocol schemes: http, data, chrome, chrome-extension, https. jquery-2.2.4.min.js:4. I run my project on XAMPP.
My HTML:
<section class="inspiration" id="three">
<div class="overlay">
<div class="container">
<div class="row">
<article class="col-md-12 text-center">
<div class="intermediate-container">
<div class="heading">
<h2>יש לכם שאלה? צרו איתי קשר</h2>
</div>
<div class="row">
<div class="col-md-3 col-sm-3"></div>
<div class="col-md-6 center-block col-sm-6 ">
<form id="mc-form" method="POST">
<div class="form-group col-xs-12 ">
<label for="name" hidden>שם פרטי</label>
<input type="text" name="name" id="name" class="cv form-control" placeholder="שם פרטי">
<span class='error-message' id='name-error'></span>
</div>
<div class="form-group col-xs-12 ">
<label for="phone" hidden>טלפון</label>
<input type="text" name="phone" id="phone" class="cv form-control" placeholder="טלפון">
<span class='error-message' id='phone-error'></span>
</div>
<div class="form-group col-xs-12 ">
<label for="email" hidden>דואר אלקטרוני</label>
<input type="email" name="email" id="email" class="cv form-control" placeholder="דואר אלקטרוני">
<span class='error-message' id='email-error'></span>
</div>
<div class="form-group col-xs-12 ">
<label for="subject" hidden>נושא</label>
<input type="text" name="subject" id="subject" class="cv form-control" placeholder="נושא">
<span class='error-message' id='subject-error'></span>
</div>
<div class="form-group col-xs-12 ">
<label for="message" hidden>הודעה</label>
<textarea name="message" id="message" class="cv form-control message" placeholder="השאירו את הודעתכם פה" rows="4" cols="50"></textarea>
<span class='error-message' id='message-error'></span>
</div>
<!-- <input type="submit" id="submit-button" class="btn btn-custom-outline " value="שלח" > -->
<button class="btn btn-custom-outline " id="submit-button">שלח</button>
<span class='error-message' id='submit-error'></span>
<span class="success">Thank's for submitting the form</span>
</form>
</div>
</div>
</div>
</article>
</div>
</div>
</div>
</section>
<!-- [/CONTACT] -->
<!-- Optional JavaScript -->
<!-- jQuery first, then Popper.js, then Bootstrap JS -->
<script src="https://code.jquery.com/jquery-2.2.4.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-validate/1.17.0/jquery.validate.min.js"></script>
<script src="js/validateform.js" ></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.12.3/umd/popper.min.js" ></script>
My validateform.js:
$(document).ready(function(){
function jsShow(id) {
$('#'+id).show();
}
function jsHide(id) {
$('#'+id).hide();
}
function producePrompt(message, promptLocation, color) {
$('#'+promptLocation).text(message).css('color', color).show();
}
jQuery.validator.addMethod("lettersonly", function(value, element) {
return this.optional(element) || /^[a-zא-ת]+(\s[a-zא-ת]+)*$/i.test(value);
}, "Letters only please");
jQuery.validator.addMethod("digitsonly", function(value, element) {
return this.optional(element) || /([0-9\s\-]{7,})(?:\s*(?:#|x\.?|ext\.?|extension)\s*(\d+))?$/.test(value);
}, "Include only digits| min :8 ");
$('.success').hide();
$("#mc-form").validate({
error: function(label) {
$(this).addClass( "error" );
},
rules: {
name: {
required: true,
lettersonly: true
},
phone: {
required: true,
digitsonly: true
},
email: {
required: true,
email: true
},
subject: {
required: true,
minlength: 2
},
message: {
required: true,
minlength: 2
}
},
messages: {
name: {
required: "Please specify your name",
lettersonly: "Letters only please"
},
phone: {
required: "Phone number is required",
digitsonly: "Include only digits| min :8 "
},
email: {
required: "Email is required",
email: "Email Invalid"
},
subject: {
required: "Subject is required"
},
message: {
required: "Message is required"
}
},
submitHandler: function(form) {
sendForm();
}
});
function sendForm() {
$('[id*="-error"]').text(''); // default hide all error messages
event.preventDefault(); // prevent form submission and therefore page reload
$.ajax({
type: 'POST',
url: './send.php',
data: $("#mc-form").serialize(),
success: function(data) {
if(data.hasOwnProperty('error')) {
Object.keys(data['error']).forEach(function(key) {
producePrompt(data['error'][key], key+'-error', 'red');
});
}
if(data.hasOwnProperty('mail_error')) {
alert('Could not send mail');
}
if(data.hasOwnProperty('success')) {
$('.success').show();
}
}
});
}
});
My send.php:
$error_msg = array();
$success_msg = array();
$data = '';
// prevent warnings or errors from displaying, else you won't get proper json result
ini_set('display_errors',0);
if ($_SERVER["REQUEST_METHOD"] == "POST") {
if (empty($_POST["name"])) {
$error_msg['name'] = "Name is required";
} else {
$name = test_input($_POST["name"]);
// check if name only contains letters and whitespace
if (!preg_match("/^[a-zA-Zא-ת ]*$/",$name)) {
$error_msg['name'] = "Only letters and white space allowed";
}
}
if (empty($_POST["email"])) {
$error_msg['email'] = "Email is required";
} else {
$email = test_input($_POST["email"]);
// check if e-mail address is well-formed
if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
$error_msg['email'] = "Invalid email format";
}
}
if (empty($_POST["phone"])) {
$error_msg['phone'] = "Phone is required";
} else {
$phone = test_input($_POST["phone"]);
// check if e-mail address is well-formed
if (!preg_match("/^(\d[\s-]?)?[\(\[\s-]{0,2}?\d{3}[\)\]\s-]{0,2}?\d{3}[\s-]?\d{4}$/i",$phone)) {
$error_msg['phone'] = "Invalid phone number";
}
}
if (empty($_POST["subject"])) {
$error_msg['subject'] = "Subject is required";
}
if (empty($_POST["message"])) {
$error_msg['message'] = "Message is required";
}
if (empty($_POST["subject"])) {
$subject = "";
} else {
$subject = test_input($_POST["subject"]);
}
if (empty($_POST["message"])) {
$message = "";
} else {
$message = test_input($_POST["message"]);
}
if (empty($error_msg)){ // note that $lastname_error does not exists
$message_body = '';
unset($_POST['submit']);
foreach ($_POST as $key => $value){
$message_body .= "$key: $value\n";
}
$to = 'xxxxxxxxx#gmail.com';
$subjectm = 'Contact Form Submit';
if (mail($to, $subjectm, $message)){
$success_msg = "Message sent, thank you for contacting us!";
$name = $email = $phone = $message = $subject = '';
} else {
$mail_error_msg = 'Could not send email';
}
}
// set output data accordingly
if(!empty($success_msg)) {
$data = array('success'=>$error_msg);
} else if(!empty($error_msg)) {
$data = array('error'=>$error_msg);
} else if(!empty($mail_error_msg)) {
$data = array('mail_error'=>$mail_error_msg);
}
// output json that you can parse with jquery
header('Content-Type: application/json');
echo json_encode($data);
}
function test_input($data) {
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
You are opening the file directly unless you configured it in Apache. The file seems to not have connection to your web server XAMPP.
You need to do following:
Copy BootstrapLandinPage directory to c:/xampp/htdocs
Add virtual host to XAMPP
Open the file C:\xampp\apache\conf\extra\httpd-vhosts.conf and add this snippet, adapted to your environment.
<VirtualHost 127.0.0.2:80>
ServerName playground.localhost
ServerAlias playground.localhost
DocumentRoot c:/xampp/htdocs/your_website
<Directory "c:/xampp/htdocs/your_website/">
Options +Indexes +Includes +FollowSymLinks +MultiViews
AllowOverride All
Require local
</Directory>
</VirtualHost>
Restart Apache in control panel of XAMPP (click XAMPP icon in bottem right in Windows)
Open browser and enter IP address 127.0.0.2 (the one you assign in virtual host)
Now you site should appear with PHP capabilities.
UPDATE
After the latest comment i add here a way to send emails via localhost.
Use a PHP library to send mails from email address of your domain provider:
Download PHPMailer
Copy the ZIP contents into a separate directory in BootstrapLandinPage. For example: lib/PHPMailer
Add these lines to the top of you process.php
require 'path/to/PHPMailer/src/Exception.php';
require 'path/to/PHPMailer/src/PHPMailer.php';
require 'path/to/PHPMailer/src/SMTP.php';
Add the example snippet on the documentation page where you downloaded the package and ajust to your needs.
Alternatively for local mailing:
Download hmailserver
Install it following their tutorial
Navigate to C:\Windows\System32\drivers\etc\hosts file and open it as administrator
Add following line:
127.0.0.1 localhost localhost.com
Add user example#localhost.com to your hmailserver
Configure mail account in your mailing app using:
Username: example#localhost.com
Password: your_password
IMAP/SMTP Server: localhost
UPDATE 2
This would be your PHP code using PHPMailer:
require 'path/to/PHPMailer/src/Exception.php';
require 'path/to/PHPMailer/src/PHPMailer.php';
require 'path/to/PHPMailer/src/SMTP.php';
$error_msg = array();
$success_msg = array();
$data = '';
// prevent warnings or errors from displaying, else you won't get proper json result
ini_set('display_errors',0);
if ($_SERVER["REQUEST_METHOD"] == "POST") {
if (empty($_POST["name"])) {
$error_msg['name'] = "Name is required";
} else {
$name = test_input($_POST["name"]);
// check if name only contains letters and whitespace
if (!preg_match("/^[a-zA-Zא-ת ]*$/",$name)) {
$error_msg['name'] = "Only letters and white space allowed";
}
}
if (empty($_POST["email"])) {
$error_msg['email'] = "Email is required";
} else {
$email = test_input($_POST["email"]);
// check if e-mail address is well-formed
if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
$error_msg['email'] = "Invalid email format";
}
}
if (empty($_POST["phone"])) {
$error_msg['phone'] = "Phone is required";
} else {
$phone = test_input($_POST["phone"]);
// check if e-mail address is well-formed
if (!preg_match("/^(\d[\s-]?)?[\(\[\s-]{0,2}?\d{3}[\)\]\s-]{0,2}?\d{3}[\s-]?\d{4}$/i",$phone)) {
$error_msg['phone'] = "Invalid phone number";
}
}
if (empty($_POST["subject"])) {
$error_msg['subject'] = "Subject is required";
}
if (empty($_POST["message"])) {
$error_msg['message'] = "Message is required";
}
if (empty($_POST["subject"])) {
$subject = "";
} else {
$subject = test_input($_POST["subject"]);
}
if (empty($_POST["message"])) {
$message = "";
} else {
$message = test_input($_POST["message"]);
}
if(!empty($error_msg)) {
$data = array('error'=>$error_msg);
outputJson($data);
} else { // note that $lastname_error does not exists
$message_body = '';
unset($_POST['submit']);
foreach ($_POST as $key => $value){
$message_body .= "$key: $value\n";
}
$to = 'xxxxxxxxx#gmail.com';
$subjectm = 'Contact Form Submit';
$mail = new PHPMailer(true);
try {
//Server settings
$mail->SMTPDebug = 2;
$mail->isSMTP();
$mail->Host = 'smtp.gmail.com';
$mail->SMTPAuth = true;
$mail->Username = 'some_user#gmail.com';
$mail->Password = 'some_password';
$mail->SMTPSecure = 'ssl';
$mail->Port = 465;
//Recipients
$mail->setFrom('some_user#gmail.com', 'Your name');
$mail->addAddress($email, $name);
//Content
$mail->isHTML(true);
$mail->Subject = 'Contact Form Submit';
$mail->Body = $message;
$mail->AltBody = preg_replace( "/\n\s+/", "\n", rtrim(html_entity_decode(strip_tags($message))) ); // For clients that do not support html / "spam control"
$mail->send();
$data = array('success'=>'Message sent, thank you for contacting us!');
outputJson($data);
} catch (Exception $e) {
$data = array('mail_error'=>'Could not send email');
outputJson($data);
//echo 'Mailer Error: ' . $mail->ErrorInfo; // Debug message that you can see in network tab in web developer browser extension
}
$name = $email = $phone = $message = $subject = '';
}
}
// return data in json format
function outputJson($data) {
// output json that you can parse with jquery
header('Content-Type: application/json');
echo json_encode($data);
exit;
}
function test_input($data) {
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
Related
I did contact form with PHP Mailer, JavaScript and Ajax call
Everything works fine, expect javascript after clicking on button. (I even recieve an email sucessfully)
My html code:
<form id="contact-form" class="contact">
<div class="col-md-6">
<input type="text" name="name" id="fullname" placeholder="Fullname">
</div>
<div class="col-md-6">
<input type="email" name="email" id="email" placeholder="Email adress">
</div>
<div class="col-md-12">
<textarea id="message" name="message" placeholder="Message"></textarea>
</div>
<div class="col-md-12">
<button id="gumb" type="button" class="btnc" onclick="validateContact();">Send</button>
</div>
</form>
</div>
<div class="col-md-12">
<div id="response_brought"></div><!-- This will display the response from the server -->
<p> </p>
</div>
JavaSript code (This works fine, but after i press button, I RECIEVE EMAIL but my last response stays the same.. it doesn't change. It display response from fullname=="" ('Please enter your fullname in the required field to proceed. Thanks.').. So I guess there is an error inside Ajax call
function validateContact() {
"use strict";
var valid = true;
var reg = /^([A-Za-z0-9_\-\.])+\#([A-Za-z0-9_\-\.])+\.([A-Za-z]{2,4})$/;
var formData = {
fullname: $("#fullname").val(),
email: $("#email").val(),
message: $("#message").val(),
};
var fullname = $("#fullname").val();
var emailreg = $("#email").val();
var message = $("#message").val();
//dataString = {'fullname': fullname, 'email': email, 'message': message, 'submitted': '1'};
if (fullname === "") { //Validation against empty field for fullname
$("#response_brought").html('<br clear="all"><div class="form_info" align="left">Please enter your fullname in the required field to proceed. Thanks.</div>');
$("#fullname").focus();
valid = false;
} else if (emailreg === "") { //Validation against empty field for email address
$("#response_brought").html('<br clear="all"><div class="form_info" align="left">Please enter your email address in the required email field to proceed. Thanks.</div>');
$("#email").focus();
valid = false;
} else if (reg.test(emailreg) === false) { //Validation for working email address
$("#response_brought").html('<br clear="all"><div class="form_info" align="left">Sorry, your email address is invalid. Please enter a valid email address to proceed. Thanks.</div>');
$("#email").focus();
valid = false;
} else if (message === "") { //Validation against empty field for email message
$("#response_brought").html('<br clear="all"><div class="form_info" align="left">Please enter your message in the required message field to proceed. Thanks.</div>');
$("#message").focus();
valid = false;
}
valid = true;
$.ajax({
type: "POST",
url: "sendemail.php",
data: formData,
success:function(data){
var response_brought = response.indexOf('Congrats');
$(".contact-form").slideUp(500);
$("#response_brought").html(response);
setTimeout(function () {
$("#response_brought").html('');
}, 10000);
},
error:function (){}
});
}
Error in my console: ERROR
And my php code:
use PHPMailer\PHPMailer\PHPMailer;
require_once 'phpmailer/src/Exception.php';
require_once 'phpmailer/src/PHPMailer.php';
require_once 'phpmailer/src/SMTP.php';
$mail = new PHPMailer(true);
$mail->IsSMTP();
$mail->Mailer = "smtp";
//$mail->SMTPDebug = 2;
$mail->SMTPAuth = True;
$mail->Host = "smtp host";
$mail->Username = "myemail";
$mail->Password = "****";
$mail->SMTPSecure = PHPMailer::ENCRYPTION_STARTTLS;
$mail->Port = '587';
$fullname = $_POST['fullname'];
$email = $_POST['email'];
$message = $_POST['message'];
$success = $error = '';
if (!empty($fullname) && !empty($email) && !empty($message)) {
try {
$mail->setFrom('myemail');
$mail->addAddress('myemail');
$mail->isHTML(true);
$mail->Subject = 'Mail poslan iz spletnega obrazca';
$mail->Body = "Ime: " . $_POST["fullname"] . "<br> Email: " . $_POST["email"] . "<br>";
$mail->Body .= $message;
$mail->send();
$success = "Message sent successfully";
} catch (Exception $e) {
$error = "Sorry message could not send, try again";
}
}
Thank you for your help
So, I needed a contact form that can send emails with a "success" prompt that appears in my form, WITHOUT reloading. I have found PHPmailer that helps with sending mail to the inbox and not spam (this alone works fine, email sent straight to inbox). I then add the JS validation then AJAX, then the PHP that deals with the JSON response.
The "success" prompt appears when I click "send" (good!) but the problem is that no email has been sent/received. The code without the AJAX works fine on both my local and web hosts perfectly. How do I optimize this so the success prompt appears and the email is sent (inbox, ideally)?
No jQuery or any extra plugins please.
Thanks in advance.
HTML:
<div class="contact-form">
<form action="mail.php" method="POST" onsubmit="return doRegister()">
<input id="mail-name" type="text" name="name" placeholder="Your Name">
<span id="name-alert"></span>
<input id="mail-email" type="text" name="email" placeholder="Your Email">
<span id="email-alert"></span>
<input id="mail-subject" type="text" name="subject" placeholder="Your Subject">
<span id="subject-alert"></span>
<textarea id="mail-message" name="message" placeholder="Your Message"></textarea>
<span id="message-alert"></span>
<input type="submit" value="Send">
<input type="reset" value="Clear">
<span class="contact__form--alert-success" id="success-alert"></span>
</form>
</div>
JS:
function doRegister() {
let checks = {
name : document.getElementById("mail-name"),
email : document.getElementById("mail-email"),
subject : document.getElementById("mail-subject"),
message : document.getElementById("mail-message")
},
error = "";
if (checks.name.value=="") {
error += document.getElementById("name-alert").innerHTML+='<p>A name is required!</p>';
}
if (checks.subject.value=="") {
error += document.getElementById("subject-alert").innerHTML+='<p>A subject is required!</p>';
}
if (checks.message.value=="") {
error += document.getElementById("message-alert").innerHTML+='<p>A message is required!</p>';
}
let pattern = /^(([^<>()\[\]\\.,;:\s#"]+(\.[^<>()\[\]\\.,;:\s#"]+)*)|(".+"))#((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
if (!pattern.test(checks.email.value.toLowerCase())) {
error += document.getElementById("email-alert").innerHTML+='<p>A valid email is required!</p>';
}
// Ajax
if (error!="") {
error="";
} else {
let data = new FormData();
for (let k in checks) {
data.append(k, checks[k].value);
}
let xhr = new XMLHttpRequest();
xhr.open('POST', "mail.php", true);
xhr.onload = function(){
let res = JSON.parse(this.response);
// SUCCESS!
if (res.status) {
document.getElementById("success-alert").innerHTML+='<p>Success!</p>';
} else {
// ERROR!
error = "";
for (let e of res['error']) {
error += e + "\n";
}
alert(error);
}
};
// SEND
xhr.send(data);
}
return false;
}
PHP:
use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\SMTP;
use PHPMailer\PHPMailer\Exception;
$error = [];
$msg = '';
if ( array_key_exists( 'email', $_POST ) ) {
date_default_timezone_set( 'Etc/UTC' );
require 'mail/vendor/autoload.php';
// Call super globals from the contact form names
$email = $_POST['email'];
$name = $_POST['name'];
$subject = $_POST['subject'];
$message = $_POST['message'];
$mail = new PHPMailer;
$mail->isSMTP();
$mail->Host = 'mail.host.com';
$mail->SMTPAuth = true;
$mail->Username = 'name#host.com';
$mail->Password = 'password1';
$mail->SMTPSecure = 'ssl';
$mail->Port = 465;
$mail->setFrom( 'name#host.com', 'New Message' );
$mail->addAddress( 'somemail#mail.com' );
if ($mail->addReplyTo($email, $name)) {
$mail->Subject = $subject;
$mail->isHTML(false);
$mail->Body = <<<EOT
Email: {$email}
Name: {$name}
Message: {$message}
EOT;
}
// Check inputs
if ($name=="") {
$error[] = "A name is required.";
}
if ($subject=="") {
$error[] = "A subject is required.";
}
if ($message=="") {
$error[] = "A message is required.";
}
if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
$error[] = "A valid email is required.";
}
// JSON encode with a response
echo json_encode([
"status" => count($error)==0 ? 1 : 0,
"error" => $error
]);
}
Solution:
the "send()" function was missing
if(empty($error)){
if(!$mail->send()){
$error[] = 'There was an error sending the mail. Please try again!';
}
}
Your PHP script doesn't send the mail because the send() function is not called, so after the validation, you should add something like:
if(empty($error)){
if(!$mail->send()){
$error[] = 'There was an error sending the mail. Please try again!';
}
}
echo json_encode([
"status" => count($error)==0 ? 1 : 0,
"error" => $error
]);
This way you're sending the mail and, if there was a problem(send() returns false), an error is being added to your error array.
I am using PhpMailer to send emails. Inside my own script I want to parse some javascript inside the below if statement. Note that I have html enabled.
When the email is not sent I want to parse some javascript inside the .done function that the email is not sent. eg complete.html("Message Not Sent!"); When the email is sent, I want to show that the email is sent. How can I do that and where is better to do that, inside php file or inside the javascript?
var form = $('#contact');
form.submit(function(event) {
event.preventDefault();
var complete = $('#formAppend');
var $form = $(this);
var name = $("#fname").val();
var email = $("#email").val();
var Message = $("#msg").val();
var countryoption = $("#country").val();
$.ajax({
type: 'POST',
url: '../sendemail.php',
data: {
Name: name,
Email: email,
message: Message,
Country: countryoption
},
beforeSend: function() {
complete.html('Message is Sending...').fadeIn();
}
})
.done(function(data) {
//This should change depending on the php if statement at the bottom.
complete.html("Message Sent");
});
}); //end contact form
<form id="contact" method="post" action="#ss">
<div id="formAppend"></div>
<input type="text" id="fname" name="firstname" placeholder="Το όνομα σας.." required>
<input type="email" id="email" name="email" placeholder="Το email σας.." required>
<select id="country" required>
<option class="w3-center" value="" disabled selected value>-- Χώρα --</option>
<option value="Κυπρος">Κύπρος</option>
<option value="Ελλάδα">Ελλάδα</option>
<option value="Άλλο">Άλλη</option>
</select>
<textarea id="msg" name="message" placeholder="Γράψε το μήνυμα.." style="height:200px;max-height:400px;min-height:100px;" required></textarea>
<div id="op">
<button type="submit" style="" class="btn btn-primary img-responsive"> Αποστολή</button> </div>
</form>
PHP:
<?php
require 'PHPMailer-master/PHPMailerAutoload.php';
if(empty($_POST['Email'])){
$_POST['Email']= "";
}
if(empty($_POST['Name'])){
$_POST['Name']= "";
}
if(empty($_POST['message'])){
$_POST['message']= "";
}
if (isset($_POST["message"]) && !empty($_POST["message"])) {
$mymail=smtpmailer("webdominar1#gmail.com",$_POST['Email'], $_POST['Name'], $_POST['message']);
}else{
header('Location: http://webdominar.xyz'); exit();
}
function smtpmailer($to, $from, $from_name, $body) {
$mail = new PHPMailer;
$mail->isSMTP();
$mail->Debugoutput = 'html';
$mail->Host = 'smtp.gmail.com';
$mail->Port = 587;
$mail->SMTPSecure = 'tls';
$mail->SMTPAuth = true;
$mail->Username = '';
$mail->Password = '';
$mail->SetFrom($from, $from_name);
$mail->Subject = "Εμβολιασμός Δέντρων ~ Φόρμα Επικοινωνίας ~ $body ";
$mail->CharSet = 'UTF-8';
$mail->isHTML(true); // Set email format to HTML
$Country = $_POST["Country"];
$mail->Body = "BLABLA ";//end email body
$mail->AddAddress($to);
//send the message, check for errors
if (!$mail->send()) { //Message not sent
echo "Mailer Error: " . $mail->ErrorInfo;
} else {//Message sent!
echo "Well done $from_name, your message has been sent!\nWe will reply to the following email: $from"
. "<br>Your Message: $body";
}
} //end function smtpmailer
?>
Change you PHP and JS code like this........
require 'PHPMailer-master/PHPMailerAutoload.php';
if (empty($_POST['Email'])) {
$_POST['Email'] = "";
}
if (empty($_POST['Name'])) {
$_POST['Name'] = "";
}
if (empty($_POST['message'])) {
$_POST['message'] = "";
}
if (isset($_POST["message"]) && !empty($_POST["message"])) {
$mymail = smtpmailer("webdominar1#gmail.com", $_POST['Email'], $_POST['Name'], $_POST['message']);
} else {
header('Location: http://webdominar.xyz');
exit();
}
function smtpmailer($to, $from, $from_name, $body) {
$mail = new PHPMailer;
$mail->isSMTP();
$mail->Debugoutput = 'html';
$mail->Host = 'smtp.gmail.com';
$mail->Port = 587;
$mail->SMTPSecure = 'tls';
$mail->SMTPAuth = true;
$mail->Username = '';
$mail->Password = '';
$mail->SetFrom($from, $from_name);
$mail->Subject = "Εμβολιασμός Δέντρων ~ Φόρμα Επικοινωνίας ~ $body ";
$mail->CharSet = 'UTF-8';
$mail->isHTML(true); // Set email format to HTML
$Country = $_POST["Country"];
$mail->Body = "BLABLA "; //end email body
$mail->AddAddress($to);
//send the message, check for errors
if (!$mail->send()) { //Message not sent
//echo "Mailer Error: " . $mail->ErrorInfo;
$responce = array(
'message' => $mail->ErrorInfo,
'success' => FALSE,
);
echo json_encode($responce);
} else {//Message sent!
$msg = "Well done $from_name, your message has been sent!\nWe will reply to the following email: $from"
. "<br>Your Message: $body";
$responce = array(
'message' => $msg,
'success' => TRUE,
);
echo json_encode($responce);
}
}
Change your JS code like this
var form = $('#contact');
form.submit(function(event) {
event.preventDefault();
var complete = $('#formAppend');
var $form = $(this);
var name = $("#fname").val();
var email = $("#email").val();
var Message = $("#msg").val();
var countryoption = $("#country").val();
$.ajax({
type: 'POST',
url: '../sendemail.php',
data: {
Name: name,
Email: email,
message: Message,
Country: countryoption
},
beforeSend: function() {
complete.html('Message is Sending...').fadeIn();
}
})
.done(function(data) {
var response=JSON.parse(data);
if(response.success == true) {
//return true
complete.html("Message Sent");
// if you want show Response message which get form sendemail.php
complete.html(data.message);
} else {
//return false
complete.html("Message Not Sent!");
// if you want show Response message which get form sendemail.php
complete.html(data.message)
}
//This should change depending on the php if statement at the bottom.
});
}); //end contact form
Change the end of your PHP to:
header("Content-type:application/json");
$message = "Well done ".$from_name.", your message has been sent!<br/>We will reply to the following email:".$from."<br>Your Message: ".$body;
if (!$mail->send()) {
echo '{"error":"'.$mail->ErrorInfo.'"}';
} else {
echo '{"success":"'.json_encode($message).'"}';
}
Then you can do this in the .done:
.done(function(data) {
if (data.error) {
complete.html(data.error).addClass("error");
}
else
complete.html(JSON.parse(data.success));
}
});
This question already has answers here:
PHP mail function doesn't complete sending of e-mail
(31 answers)
Closed 6 years ago.
I have made a "forgot password" page so when the user submits their emailid, then email matches from database and if email exists then password is sent to that email. The mail() function is used to send the email. If I submit then message shows
Password sent to your email id. Please check your email now!
But message is not going in INBOX or SPAM. My hosting is LINUX hosting.
<form method="post" id="loginForm" name="loginForm" action="" onsubmit="return executeOnSubmit();">
<div class="col-lg-4" style="text-align:right;">
Email ID <span style="color:red">*</span>
</div>
<div class="col-lg-8">
<input type="email" class="form-control" value="<?php echo $email; ?>" name="email" placeholder="Enter email address" required />
</div>
<div style="clear:both;"><br /></div>
<div class="col-lg-4"></div>
<div class="col-lg-8 pull-right">
<input type="submit" class="btn btn-success" value="Submit" name="submit" />
</div>
</form>
<?php
$email = "";
if(isset($_POST["submit"]))
{
$email = $_POST["email"];
$res=mysql_query("select * from mainaccount where email='$email'") or die(mysql_error());
if($row = mysql_fetch_array($res))
{
extract($row);
$msg = "Hi User,\n\nEmail: ".$email."\n\nPassword: ".$password;
$smail=mail($email,"Scholarship Forgot Password!","Forgot Password Details: ",$password);
if(!$smail)
{
echo "<span style='color:red;'> — Mail Not Send!</span>";
}
else
{
echo " — Password sent to your email id. Please check your email now!";
}
}
else
{
echo "<span style='color:red;'>Email id does not match!</span>";
}
}
?>
You can use PHPMailer. Download the library from https://github.com/PHPMailer/PHPMailer.
<?php
function send_mail($email, $recipient_name, $subject, $message='')
{
require("phpmailer/class.phpmailer.php");
$mail = new PHPMailer();
$mail->CharSet="utf-8";
$mail->IsSMTP(); // set mailer to use SMTP
$mail->Host = "mail.example.com"; // specify main and backup server
$mail->SMTPAuth = true; // turn on SMTP authentication
$mail->Username = "myusername"; // SMTP username
$mail->Password = "p#ssw0rd"; // SMTP password
$mail->From = "me#walalang.com";
$mail->FromName = "System-Ad";
$mail->AddAddress($email, $recipient_name);
$mail->WordWrap = 50; // set word wrap to 50 characters
$mail->IsHTML(true); // set email format to HTML (true) or plain text (false)
$mail->Subject = $subject;
$mail->Body = $message;
$mail->AltBody = "This is the body in plain text for non-HTML mail clients";
// $mail->AddEmbeddedImage('images/logo.png', 'logo', 'logo.png');
//$mail->addAttachment('files/file.xlsx');
if(!$mail->Send())
{
return false;
}
return true;
}
$email = "";
if(isset($_POST["submit"]))
{
$email = $_POST["email"];
$res=mysql_query("select * from mainaccount where email='$email'") or die(mysql_error());
if($row = mysql_fetch_array($res))
{
extract($row);
$msg = "Hi User,\n\nEmail: ".$email."\n\nPassword: ".$password;
$smail= send_mail($email,"User name","Scholarship Forgot Password!",msg);
if(!$smail)
{
echo "<span style='color:red;'> — Mail Not Send!</span>";
}
else
{
echo " — Password sent to your email id. Please check your email now!";
}
}
else
{
echo "<span style='color:red;'>Email id does not match!</span>";
}
}
?>
I have an update password page that won't let me enter the actual current password for the current password field. Instead, it wants the hashed password. Once changed however, the new one is then hashed, which is a good thing. I just need to be able to enter the actual password and not hashed.
Yes I know, no md5; this is more for testing is all.
changepassword.js
<script>
function validatePassword() {
var currentPassword,newPassword,confirmPassword,output = true;
currentPassword = document.frmChange.currentPassword;
newPassword = document.frmChange.newPassword;
confirmPassword = document.frmChange.confirmPassword;
if(!currentPassword.value) {
currentPassword.focus();
document.getElementById("currentPassword").innerHTML = "required";
output = false;
}
else if(!newPassword.value) {
newPassword.focus();
document.getElementById("newPassword").innerHTML = "required";
output = false;
}
else if(!confirmPassword.value) {
confirmPassword.focus();
document.getElementById("confirmPassword").innerHTML = "required";
output = false;
}
if(newPassword.value != confirmPassword.value) {
newPassword.value="";
confirmPassword.value="";
newPassword.focus();
document.getElementById("confirmPassword").innerHTML = "not same";
output = false;
}
return output;
}
</script>
updatepassword.php
<?php
include 'core/login.php'; === this contains the connection, it's obviously good ===
include 'includes/head.php'; === changepassword.js is linked in the head ===
if(count($_POST)>0) {
$result = mysqli_query($link, "SELECT *from users WHERE id='" . $_SESSION["id"] . "'");
$row = mysqli_fetch_array($result);
if($_POST["currentPassword"] == $row["password"]) {
mysqli_query($link, "UPDATE users set `password`='" .md5(md5($_POST['newPassword'])) . "' WHERE id='" . $_SESSION["id"] . "'");
$message = "Password Changed";
} else $errormessage = "Current Password is not correct";
}
print_r($_SESSION);
?>
form on same page:
<div class="container">
<div class="text-center">
<h4>Change password below</h4>
</div><br />
<div class="message"><?php if(isset($message)) { echo $message; } ?></div>
<div class="message"><?php if(isset($errormessage)) { echo $errormessage; } ?></div>
<div class="col-md-4 col-md-offset-4">
<form name="frmChange" method="post" action="" onSubmit="return validatePassword()">
<div class="form-group">
<label>Current Password*</label>
<input type="text" name="currentPassword" class="form-control input-md" />
</div>
<div class="form-group">
<label>New Password*</label>
<input type="text" name="newPassword" class="form-control input-md" />
</div>
<div class="form-group">
<label>Confirm Password*</label>
<input type="text" name="confirmPassword" class="form-control input-md" />
</div>
<br />
<div class="text-center">
<input type="submit" name="submit" class="btn btn-success" value="Submit" />
</div>
</form>
</div>
</div>
Your problem is here:
if($_POST["currentPassword"] == $row["password"]) {
You are comparing the actual text version of the hash (say "password") to the hashed version of that password (say "213y789hwuhui1dh"). This evaluates out to:
if("password" == "213y789hwuhui1dh") {
Which obviously is never accurate. All you have to do to solve the problem is hash the password in the same way you did when you created it. If I understand your code properly, that should be:
if(md5(md5($_POST["currentPassword"]))==$row["password"]) {
SIDE NOTE ON SQL INJECTION
Please note that this code would be super easy to inject into. All a user would have to do is end the "currentPassword" POST value with '; SHOW DATABASE; and they would have unlimited access to your server's MySQL database. Consider learning to use MySQLi Prepared Statements. They are easy to understand, and easy to implement.
I went overboard. Your other question was closed. Juuuuust gonna leave this here... I'm using PHP version PHP 5.2.0.
http://php.net/manual/en/faq.passwords.php
http://php.net/manual/en/function.password-hash.php
http://php.net/manual/en/function.password-verify.php
<?php
// so I don't actually have to test form submission, too...
$_POST['current_password'] = 'Tacotaco';
$_POST['new_password'] = 'NINrocksOMG';
$_POST['confirmPassword'] = 'NINrocksOMG';
$_SESSION['id'] = 1;
// this is Tacotaco encrypted... update your db to test
// update users set password = '$2y$10$fc48JbA0dQ5dBB8MmXjVqumph1bRB/4zBzKIFOVic9/tqoN7Ui59e' where id=1
// the following is sooooo ugly... don't leave it this way
if (!isset($_SESSION['id']) or empty($_SESSION['id']) or
!isset($_POST['current_password']) or empty($_POST['current_password']) or
!isset($_POST['new_password']) or empty($_POST['new_password']) or
!isset($_POST['confirmPassword']) or empty($_POST['confirmPassword']) ) {
$message = 'Please enter your password';
}
else {
$sid = $_SESSION['id'];
$currpass = $_POST['current_password'];
$newpass = $_POST['new_password'];
$conpass = $_POST['confirmPassword'];
$message = validate_password($sid, $currpass, $newpass, $conpass);
}
print "<br/>$message<br/>";
function validate_password($sid, $currpass, $newpass, $conpass) {
$mysqli = mysqli_connect('localhost','root','','test')
or die('Error ' . mysqli_error($link));
$stmt = $mysqli->prepare('select id, password from users where id = ?');
$stmt->bind_param("s", $sid);
$stmt->execute();
$stmt->bind_result($userid, $userpass);
$message = '';
if ($stmt->fetch()) {
$stmt->close();
if (strlen($newpass) < 8) {
$message = 'Please enter a password with at least 8 characters';
}
elseif (!preg_match('`[A-Z]`', $newpass)) {
$message = 'Please enter at least 1 capital letter';
}
elseif ($newpass !== $conpass) {
$message = 'Your passwords do not match.';
}
else {
if (password_verify($currpass, $userpass)) {
$hashed_new = password_hash($newpass, PASSWORD_BCRYPT);
$query = 'update users set password = ? where id = ?';
$stmt_new = $mysqli->prepare($query);
$stmt_new->bind_param('ss', $hashed_new, $sid);
if ($stmt_new->execute()) {
$message = 'Password Changed';
}
else {
$message = $mysqli->error;
}
}
else $message = 'Current Password is not correct';
}
}
else {
$message = 'user not found for id $sid';
}
$mysqli->close();
return $message;
}
?>