I have a pretty simple form in html from which i am trying to send an email. I checked online for some tutorials sing js but most of them were not working. Here is my code the form is there but when i press submit the js function is not getting called rather it is not doing anything on the html form.
<form class="form-inline" id="contact-form" onSubmit="return false">
<center><p><input style="height:3vw;width:40vw;font-size:1.2vw;" type="text" class="form-control" size="30" placeholder=" Name" name="name" id="name" required></p>
<p><input style="height:3vw;width:40vw;font-size:1.2vw;" type="email" class="form-control" size="30" placeholder=" E-mail Address" name="email" id="email" required></p>
<p><input style="height:3vw;width:40vw;font-size:1.2vw;" type="text" class="form-control" size="30" placeholder=" Subject" name="subject" id="subject" required></p>
<p><textarea style="height:10vw;width:40vw;font-size:1.2vw;" placeholder=" Message..." class="form-control" name="message" id="message"></textarea></p>
<p><button type="submit" class="button" name="btn_submit" id="btn_submit">Send</button></p></center>
</form>
i have included the js file as it is after the <div> ending of the form
<script src="js/jquery-2.1.4.js"></script>
<script src="js/bootstrap.min.js"></script>
<script src="js/functions.js"></script>
functions.js file is as follows
//Contact Us
$("#btn_submit").click(function() {
//get input field values
var user_name = $('input[name=name]').val();
var user_email = $('input[name=email]').val();
var user_message = $('textarea[name=message]').val();
//simple validation at client's end
var proceed = true;
if(user_name==""){
proceed = false;
}
if(user_email==""){
proceed = false;
}
if(user_message=="") {
proceed = false;
}
//everything looks good! proceed...
if(proceed)
{
//data to be sent to server
post_data = {'userName':user_name, 'userEmail':user_email, 'userMessage':user_message};
//Ajax post data to server
$.post('contact_me.php', post_data, function(response){
//load json data from server and output message
if(response.type == 'error')
{
output = '<div class="alert-danger">'+response.text+'</div>';
}else{
output = '<div class="alert-success">'+response.text+'</div>';
//reset values in all input fields
$('.form-inline input').val('');
$('.form-inline textarea').val('');
}
$("#result").hide().html(output).slideDown();
}, 'json');
}
});
and my email handler is as follows :
<?php
if($_POST)
{
$to_Email = "email.com"; //Replace with recipient email address
//check if its an ajax request, exit if not
if(!isset($_SERVER['HTTP_X_REQUESTED_WITH']) AND strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) != 'xmlhttprequest') {
//exit script outputting json data
$output = json_encode(
array(
'type'=>'error',
'text' => 'Request must come from Ajax'
));
die($output);
}
//check $_POST vars are set, exit if any missing
if(!isset($_POST["userName"]) || !isset($_POST["userSubject"]) || !isset($_POST["userEmail"]) || !isset($_POST["userMessage"]))
{
$output = json_encode(array('type'=>'error', 'text' => 'Input fields are empty!'));
die($output);
}
//Sanitize input data using PHP filter_var().
$user_Name = filter_var($_POST["userName"], FILTER_SANITIZE_STRING);
$user_Email = filter_var($_POST["userEmail"], FILTER_SANITIZE_EMAIL);
$user_Subject = filter_var($_POST["userSubject"], FILTER_SANITIZE_STRING);
$user_Message = filter_var($_POST["userMessage"], FILTER_SANITIZE_STRING);
//additional php validation
if(strlen($user_Name)<3) // If length is less than 3 it will throw an HTTP error.
{
$output = json_encode(array('type'=>'error', 'text' => 'Name is too short or empty!'));
die($output);
}
if(!filter_var($user_Email, FILTER_VALIDATE_EMAIL)) //email validation
{
$output = json_encode(array('type'=>'error', 'text' => 'Please enter a valid email!'));
die($output);
}
if(strlen($user_Message)<5) //check emtpy message
{
$output = json_encode(array('type'=>'error', 'text' => 'Too short message! Please enter something.'));
die($output);
}
$subject = $user_Subject;
$message_Body = "<strong>Name: </strong>". $user_Name ."<br>";
$message_Body .= "<strong>Email: </strong>". $user_Email ."<br>";
$message_Body .= "<strong>Message: </strong>". $user_Message ."<br>";
$headers = "From: " . strip_tags($user_Email) . "\r\n";
$headers .= "Reply-To: ". strip_tags($user_Email) . "\r\n";
$headers .= "MIME-Version: 1.0\r\n";
$headers .= "Content-Type: text/html; charset=ISO-8859-1\r\n";
//proceed with PHP email.
/*$headers = 'From: '.$user_Email.'' . "\r\n" .
'Reply-To: '.$user_Email.'' . "\r\n" .
'X-Mailer: PHP/' . phpversion();
*/
$sentMail = #mail($to_Email, $subject, $message_Body, $headers);
if(!$sentMail)
{
$output = json_encode(array('type'=>'error', 'text' => 'Could not send mail! Please check your PHP mail configuration.'));
die($output);
}else{
$output = json_encode(array('type'=>'message', 'text' => 'Hi '.$user_Name .' Thank you for contacting us.'));
die($output);
}
}
?>
On pressing submit the js file is not being called and there is no error in console either. Can anyone please help me out where i am making the mistake. Thank you.
You need to prevent the default form submission action which is to refresh the page.
You need to add a parameter to your function that can track the event and then call preventDefault() from that parameter:
$("#btn_submit").click(function(e) {
e.preventDefault();
...
}
Try replacing
$("#btn_submit").click(function() {
with
$(document).on("click,", "#btn_submit", function(){
You need to prevent the form from submitting, otherwise it will just directly submit and turn to the server-side.
You can do such a thing using jQuery:
$("#btn_submit").click(function(e) {
e.preventDefault();
//your code goes here after preventing submission
}
Related
I have a form that uses an HTML form, http post request, and PHP backend to automatically send me the data that a user inputs into the form. The submission works as expected, but I am not getting an email. My email is also run by outlook. Not sure if it's an encryption thing.
HTML Code
<form action="mail.php" method="POST">
<div class="email-box">
<input class="tbox" id="email_box" name="email" type="email" style="cursor: pointer;" placeholder="Enter your email">
<button class="btn" id="email_btn" type="submit" name="button">Subscribe</button>
</div>
</form>
<!-- Snipped JavaScript validation -->
PHP
<?php
$errors = '';
$myemail = 'me#website.com';
if (empty($_POST['email'])) {
$errors .= "\n Error: all fields are required";
}
$email_address = $_POST['email'];
if (!preg_match(
"/^[_a-z0-9-]+(\.[_a-z0-9-]+)*#[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,3})$/i",
$email_address)) {
$errors .= "\n Error: Invalid email address";
}
if (empty($errors)) {
$to = $myemail;
$email_subject = "New Vrify subscription: $email_address";
$email_body = "You have a new subscriber. " .
"Here are the details:\n Email: $email_address \n " .
$headers = "From: subscriber#website.com";
mail($to, $email_subject, $email_body, $headers);
//redirect to the 'thank you' page
header('Location: thank-you.html');
}
?>
This may not be the full solution, but as far as I'm aware
"New Vrify subscription: $email_address"
is not valid. Instead, concatenate them using the . operator
"New Vrify subscription:".$email_address
Do the same to the other variables you have, I had the same issue when working on the following php:
if (($_SERVER["REQUEST_METHOD"] ?? 'GET') == "POST") {
$msg ="New message from mysite!\n".$_POST["message"]."\nReply Email:".$_POST["email"];
mail("me#gmail.com", time(), $msg,"From: contact#mysite");
}
I'm trying to send an email to myself with the text that has been entered in the textbox.
<form class="form align-center" id="mailchimp">
<div class="row">
<div class="col-md-8 col-md-offset-2">
<div class="newsletter-label font-alt">
Stay informed with our newsletter
</div>
<div class="mb-20">
<input placeholder="Enter Your Email" class="newsletter-field form-control input-md round mb-xs-10"
name="emaill" type="email" pattern=".{5,100}" required aria-required="true">
<button type="submit" aria-controls="subscribe-result" id="submit_btnn"
class="btn btn-mod btn-medium btn-round mb-xs-10">
Subscribe
</button>
</div>
<div class="form-tip">
<i class="fa fa-info-circle"></i> Please trust us, we will never send you spam
</div>
<div id="subscribe-result" role="region" aria-live="polite" aria-atomic="true"></div>
After that I catch it in Js
$(document).ready(function(){
$("#submit_btnn").click(function(){
//get input field values
var user_email = $('input[name=emaill]').val();
//simple validation at client's end
var proceed = true;
//we simply change border color to red if empty field using .css()
if (user_email == "") {
$('input[name=email]').css('border-color', '#e41919');
proceed = false;
}
//everything looks good! proceed...
if (proceed) {
//data to be sent to server
post_data = {
'userEmail': user_email
};
console.log(post_data);
//Ajax post data to server
$.post('nieuwsbrief.php', post_data, function(response){
//load json data from server and output message
if (response.type == 'error') {
output = '<div class="error">' + response.text + '</div>';
}
else {
output = '<div class="success">' + response.text + '</div>';
}
$("#subscribe-result").hide().html(output).slideDown();
}, 'json');
}
return false;
});
//reset previously set border colors and hide all message on .keyup()
$("#contact_form input, #contact_form textarea").keyup(function(){
$("#contact_form input, #contact_form textarea").css('border-color', '');
$("#subscribe-result").slideUp();
});
});
After that I want to use the Ajax post to send it to my php file
<?php
if($_POST)
{
echo '<script>console.log($_POST["userEmail"])</script>';
$to_Email = "mathias#wizewolf.com"; //Replace with recipient email address
$subject = 'Message from website '.$_SERVER['SERVER_NAME']; //Subject line for emails
echo '<script>console.log(to_Email)</script>';
//check if its an ajax request, exit if not
if(!isset($_SERVER['HTTP_X_REQUESTED_WITH']) AND strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) != 'xmlhttprequest') {
//exit script outputting json data
$output = json_encode(
array(
'type'=>'error',
'text' => 'Request must come from Ajax'
));
die($output);
}
//check $_POST vars are set, exit if any missing
if(!isset($_POST["userEmail"]))
{
$output = json_encode(array('type'=>'error', 'text' => 'Input fields are empty!'));
die($output);
}
//Sanitize input data using PHP filter_var().
$user_Email = filter_var($_POST["userEmail"], FILTER_SANITIZE_EMAIL);
$user_Message = "d";
$user_Message = str_replace("\'", "'", $user_Message);
$user_Message = str_replace("'", "'", $user_Message);
//additional php validation
if(strlen($user_Name)<4) // If length is less than 4 it will throw an HTTP error.
{
$output = json_encode(array('type'=>'error', 'text' => 'Name is too short or empty!'));
die($output);
}
if(!filter_var($user_Email, FILTER_VALIDATE_EMAIL)) //email validation
{
$output = json_encode(array('type'=>'error', 'text' => 'Please enter a valid email!'));
die($output);
}
if(strlen($user_Message)<5) //check emtpy message
{
$output = json_encode(array('type'=>'error', 'text' => 'Too short message! Please enter something.'));
die($output);
}
//proceed with PHP email.
$headers = 'From: '.$user_Email.'' . "\r\n" .
'Reply-To: '.$user_Email.'' . "\r\n" .
'X-Mailer: PHP/' . phpversion();
$sentMail = #mail($to_Email, $subject, $user_Message . "\r\n\n" .'-- '.$user_Name. "\r\n" .'-- '.$user_Email, $headers);
if(!$sentMail)
{
$output = json_encode(array('type'=>'error', 'text' => 'Could not send mail! Please check your PHP mail configuration.'));
die($output);
}else{
$output = json_encode(array('type'=>'message', 'text' => 'Hi '.$user_Name .'! Thank you for your email'));
die($output);
}
}
?>
With the console log, I've found out that until the start of the PHP file everything works. After that... not so much. All the tips and info are appreciated.
Instead of using jQuery and PHP, you could use STMP.js. I don't know how to answer this question with jQuery or PHP, but I know how to send emails with SMTP. I made an example on JSFiddle below. But, this might not work on JSFiddle for security reasons.
JSFiddle
https://jsfiddle.net/Yeet45687564/9prs4j2a/21/
// the javascript code below is also found on JSFiddle
let subject;
let body;
function setValues() {
// sets the values of the subject and body
subject = document.getElementById("emailSubject").value;
body = document.getElementById("emailBody").value;
}
function send() {
setValues();
// sends the email
Email.send({
Host: "smtp.gmail.com",
Username: "<sender's email address>",
Password: "<your email password>",
To: "<recipient's email address>",
From: "<sender’s email address>",
Subject: subject,
Body: body,
}).then(
// displays a message if the email was sent
message => alert("Your Email was sent.")
);
}
If you can't get this working, there is an SMTP tutorial on Pepipost.
https://pepipost.com/tutorials/how-to-send-emails-with-javascript/
But, using SMTP could be a huge security issue. Anyone who uses the inspect element on your website will be able to get your email password, unless you can block them from inspecting it and viewing the page source.
I've currently got a working PHP/AJAX form. It shows a form-message when the form is sent, or when it has an error. But, the page doesn't refresh when the form is sent, so it'll be easy to send multiple emails by just a simple double click (or even more clicks). Have a look at my code:
HTML
<form action="" method="POST">
<ul class="form-style-1">
<li>
<input type="text" id="mail-name" name="name" class="field-divided" maxlength="15" placeholder="Voornaam *" /> <input type="text" id="mail-lastname" name="lastname" class="field-divided" maxlength="15" placeholder="Achternaam" >
</li>
<li>
<input type="text" id="mail-email" name="email" placeholder="E-mail *" class="field-long" maxlength="40" >
</li>
<li>
<input type ="text" id="mail-phone" name="phone" placeholder="Telefoonnummer" class="field-long" maxlength = "15">
</li>
<button class="mail-submit" id="mail-submit" type="submit" name="submit">Versturen</button>
<span style="color: #0184b2; text-align: center; font-size: 20px; margin: 0 auto; display: block; padding-top: 10px;" class="form-message"></span>
</ul>
</form>
JS
$("form").on("submit",function(event){
event.preventDefault();
var name = $("#mail-name").val();
var lastname = $("#mail-lastname").val();
var email = $("#mail-email").val();
var phone = $("#mail-phone").val();
var subject = $("#mail-subject").val();
var information = $("#mail-information").val();
$.post("donation-contact.php",
{
name: name,
lastname: lastname,
email: email,
phone: phone,
submit: "yes"
},
function(data){
$(".form-message").html( data );
}
);
});
PHP
<?php
if (isset($_POST['submit'])) {
$email_to = "#";
$email_subject = "#";
$name = $_POST['name'];
$lastname = $_POST['lastname'];
$email = $_POST['email'];
$phone = $_POST['phone'];
$errorEmpty = false;
$errorEmail = false;
if (empty($name)) {
echo "<span class='form-error'>Voer de verplichte velden in!</span>";
$errorEmpty = true;
}
elseif (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
echo "<span class='form-error'>Geef een geldig E-mail!</span>";
$errorEmail = true;
}
else {
$formcontent=" Naam: $name \n\n Achternaam: $lastname \n\n Email: $email \n\n Telefoon: $phone";
$mailheader = "From: ".$_POST["email"]."\r\n";
$headers = "From: ". htmlspecialchars($_POST['name']) ." <" . $_POST['email'] . ">\r\n";
$headers .= "Reply-To: " . $_POST['email'] . "\r\n";
$headers .= "MIME-Version: 1.0\r\n";
$headers .= "Content-Type: text/html; charset=ISO-8859-1\r\n";
mail($email_to, $email_subject, $formcontent, $mailheader);
echo "<span class='form-success'>De mail is verzonden!</span>";
}
}
?>
I've tried disabling the form button when it's being pressed. This works if the user doesn't make any mistakes, but it will also disable the button when it shows an error message.
Is there a way to disable the button only when the form is sent? Or to remove all the form input when the form is sent?
Thank you for your time
All you need is basically already present in your code.
You intercept the submission via
$("form").on("submit",function(event){
event.preventDefault();
// ...
This is the place to disable the submit button:
$("form").on("submit",function(event){
event.preventDefault();
$('#mail-submit').prop('disabled', true);
// ...
});
But you need a different treatment in the PHP script so that you can handle errors. Basiacally you need to send back a JSON object which will have a simple text property indicating the status (error / success) and a text property for the message (which may contain HTML).
PHP
if (empty($name)) {
$response = array('status' => 'error', 'message' => '<span class='form-error'>Voer de verplichte velden in!</span>');
$errorEmpty = true;
}
elseif (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
$response = array('status' => 'error', 'message' => '<span class='form-error'>Geef een geldig E-mail!</span>');
$errorEmail = true;
}
else {
// send email...
$response = array('status' => 'success', 'message' => '<span class='form-success'>De mail is verzonden!</span>');
}
// No matter what happened, send the respons as a JSON object for easy treatment in JavaScript
echo json_encode($response);
Now in JavaScript you will receive an object, instead of text in you callback function:
function(data) {
$(".form-message").html( data.message );
// If there was an error you must re-enable the submit button
if (data.status === 'error') {
$('#mail-submit').prop('disabled', false);
}
}
So I'm having some issues getting my validation which resides in my php action script.
I have the following form:
<form action="contact.php" method ="post" enctype="multipart/form-data" id="contact_form" name="contact_form">
<div class="div_input"><input name="name" type="text" value="Name: " class="input4" /></div>
<div class="div_input"><input name="phone" type="text" value="Phone: " class="input4" /></div>
<div class="div_input"><input name="email" type="text" value="E-mail: " class="input4" /></div>
<textarea name="message" cols="0" rows="0" class="textarea2" >Message: </textarea>
Then I am submitting using the onclick() method. This is where my issue is arising I believe.
<div class="link4"><span>send</span></div>
<div class="link4"><span>clear</span></div>
</form>
And my script...
<?php
$errors = '';
$myemail = 'test#test.com';
$name = $phone = $email = $message ='';
$nameError = $emailError =$phoneError = $messageError = '';
if(empty($_POST['name']))
{$nameError='Name is required!';}
else
{
$name = test_input($_POST['name']);
// check if name only contains letters and whitespace
if (!preg_match("/^[a-zA-Z ]*$/",$name))
{
$nameError='Only letters and white space allowed';
}
}
if(empty($_POST['email']))
{$emailError='Email is required!';}
else
{
$email = test_input($_POST['email']);
//check to make sure is a valid email format
if(!preg_match("/([\w\-]+\#[\w\-]+\.[\w\-]+)/",$email))
{
$emailError = "Invalid email format!";
}
}
if(empty($_POST['phone']))
{
'Phone number is required';
}
else
{
$phone = test_input($_POST['phone']);
//Allow only digits in the phone number
if(!preg_match("/^[\d\-]+$/",$phone));
{
$phoneError = 'Phone must be only numbers and dashes';
}
}
if (empty($_POST['message']))
{
$messageError = 'Message is required!';
}
else
{
$message = test_input($_POST['message']);
}
function test_input($data)
{
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
$to = $myemail;
$email_subject = "Contact form submission: $name";
$email_body = "You have received a new message. ".
" Here are the details:\n Name: $name \n ".
"Email: $email\n Phone Number: $phone\n Message \n $message";
$headers = "From: $email \r\n";
$headers .= "Reply-To: $email";
mail($to,$email_subject,$email_body,$headers);
//redirect to the 'thank you' page
//header('Location: index-5.html');
?>
When I test this, no validation runs at all. I can click send with the form empty and no errors appear.
I've seen a couple people having issues with the javascript onclick function and validation in their php script. Could this be it? Or am I missing something in my script or form? I'm thinking maybe I need to add some javascript after the submit() method.
What do you all think?
The main problem is that your PHP script is sending the message regardless of whether or not there's an error.
Try checking whether $nameError, $emailError,$phoneError, and $messageError are all empty strings before submitting.
Other suggested improvements:
Read up on PHP's filter functions and use them instead of your regular expressions.
Take advantage of HTML5 validation in browsers that support it by adding required to all of your input fields.
Use <input type="submit" value="send"> and <input type="reset" value="clear"> instead of onclick. They're a little bit harder to style with CSS, but it's better for accessibility and works even when JavaScript doesn't.
One thing I see is
if(empty($_POST['phone']))
{
'Phone number is required';
}
should be
if(empty($_POST['phone']))
{
$phoneError = 'Phone number is required';
}
I have this landing page with contact form which is working without any problems on my regular hosting but It doesn't want to work on this VPS I was given access to. When I click "Send" button nothing is happening and email is not being sent. I checked mail() function and it seems to work on their server.
What could be the reason for ajax/json not working on this server?
Here's the JS code (core.js):
if ($('#contact').is(":visible")) {
$("#contact button").click(function() {
var name = $("#contactname").val();
var message = $("#contactmessage").val();
var email = $("#contactemail").val();
var emailReg = /^[a-zA-Z0-9._+-]+#[a-zA-Z0-9-]+\.[a-zA-Z]{2,4}(\.[a-zA-Z]{2,3})?(\.[a-zA-Z]{2,3})?$/;
// client-side validation
if(emailReg.test(email) == false) {
var emailValidation = false;
$('#contactemail').addClass("error");
}
else
$('#contactemail').removeClass("error");
if(name.length < 1) {
var nameValidation = false;
$('#contactname').addClass("error");
}
else
$('#contactname').removeClass("error");
if(message.length < 1) {
var messageValidation = false;
$('#contactmessage').addClass("error");
}
else
$('#contactmessage').removeClass("error");
if ((nameValidation == false) || (emailValidation == false) || (messageValidation == false))
return false;
$.ajax({
type: "post",
dataType: "json",
url: "send-email.php",
data: $("#contact").serialize(),
success: function(data) {
$('.form').html('<p class="success">Email sent. Thank you.</p>');
}
});
return false;
});
};
The PHP file (send-email.php):
<? if($_SERVER['REQUEST_METHOD'] == "POST" ) {
$destination = 'myemail#example.com'; // change this to your email.
$email = $_POST['email'];
$name = $_POST['name'];
$message = $_POST['message'];
$subject = $name;
$headers = "From: ".$name." <".$email.">\r\n" .
"Reply-To: ".$name." <".$email.">\r\n" .
"X-Mailer: PHP/" . phpversion() . "\r\n" .
"MIME-Version: 1.0\r\n" .
"Content-Type: text/plain; charset=\"iso-8859-1\r\n" .
"Content-Transfer-Encoding: 8bit\r\n\r\n";
mail($destination, $subject, $message, $headers);
}
And HTML:
<form class="contact" id="contact">
<div class="form">
<input type="text" name="name" placeholder="Name" id="contactname" />
<input type="text" name="email" placeholder="Email" id="contactemail" />
<textarea name="message" placeholder="Message" id="contactmessage"></textarea>
<button>Send</button>
</div>
</form>
The statement var emailValidation = false; inside IF is makes the variable emailValidation local to it. Similarly other variables too are local. Declare them in global scope, outside the conditions.
try using
$("#contact").serializeArray()