PHP js alert message when form was sent ok - javascript

I'm trying to show an alert box saying the message was sent OK, but for some reason I don't see the message. I do get the one saying to check the captcha. What am I doing wrong? All the code is in my index.php file. All the if's at the beginning where attempts to avoid resubmitting the form.
Also, how can I style the alert box? I've tried using Bootbox. Js but without luck.
<?php
$message['message'] = "";
if (($_SERVER['REQUEST_METHOD'] == 'POST') && isset($_POST['submit'])) {
if (isset($_POST['g-recaptcha-response']) && ($_POST["g-recaptcha-response"] != '')) {
$url = 'https://www.google.com/recaptcha/api/siteverify';
$privatekey = "--secretKey--";
$response = file_get_contents($url."?secret=".$privatekey."&response=".$_POST['g-recaptcha-response']."&remoteip=".$_SERVER['REMOTE_ADDR']);
$data = json_decode($response);
if (isset($data->success) AND $data->success==true) {
$to = "info#someone.com.ar";
$email = $_POST['email'];
$name = $_POST['name'];
$subject = $_POST['asunto'];
$subject2 = 'Copia de: '.$_POST['asunto'];
$message = $name . " " . "escribio lo siguiente:" . "\n\n" . $_POST['message'];
$message2 = "Le enviamos una copia de su mensaje " . $name . "\n\n" . $_POST['message'];
$headers = "From:" . $email;
$headers2 = "From:" . $to;
mail($to,$subject,$message,$headers);
mail($email,$subject2,$message2,$headers2);
//echo "La consulta se envió correctamente. Gracias! " . $name . ", lo contactaremos a la brevedad.";
echo '<script type="text/javascript">alert("El mensaje se envió correctamente. Muchas gracias!");</script>';
//Back to the web
header('Location: index.php');
}
} else {
echo '<script type="text/javascript">alert("Por favor tildar el captcha!");</script>';
//$_SESSION['form'] = filter_input_array(INPUT_POST);
}
}
?>
Form:
<div class="col-md-4 to-animate">
<h3 class="section-title">Escribinos</h3>
<form class="contact-form" action="" method="post" id="form">
<div class="form-group">
<label for="name" class="sr-only">Nombre</label>
<input type="name" class="form-control" name="name" id="name" placeholder="Nombre y Apellido" required title="Por favor ingrese su nombre y apellido" value="<?php echo (isset($_POST['name']) ? htmlspecialchars($_POST['name']) : ''); ?>" />
</div>
<div class="form-group">
<label for="asunto" class="sr-only">Asunto</label>
<input type="asunto" class="form-control" name="asunto" id="asunto" placeholder="Asunto" required title="Por favor ingrese el asunto" value="<?php echo (isset($_POST['asunto']) ? htmlspecialchars($_POST['asunto']) : ''); ?>" />
</div>
<div class="form-group">
<label for="email" class="sr-only">Email</label>
<input type="email" class="form-control" name="email" id="email" placeholder="Email" required title="Por favor ingrese un mail" value="<?php echo (isset($_POST['email']) ? htmlspecialchars($_POST['email']) : ''); ?>" />
</div>
<div class="form-group">
<label for="message" class="sr-only">Mensaje</label>
<textarea class="form-control" id="message" name="message" rows="7" placeholder="Mensaje" required title="Por favor ingrese un mensaje mayor a 10 caractéres."><?php echo (isset($_POST['message']) ? htmlspecialchars($_POST['message']) : ''); ?></textarea>
</div>
<div class="form-group">
<input type="submit" name="submit" id="btn-submit" class="btn btn-send-message btn-md" value="ENVIAR">
</div>
<div class="g-recaptcha" data-sitekey="--Sitekey--" data-callback="callback"></div>
</form>
</div>

Don't know about the rest of the code or if this is the problem - but you shouldn't use "AND" in the 'if' statetement - it should be :
if (isset($data->success) && $data->success==true) {...

After removing the
header('Location: index.php');
The message appears. Don't ask me why.

Related

Php form validation with Ajax and jQuery

Everything works fine with php ,error messages function properly but if i try to do it with ajax it doesnt work. I used diffrent jQuery codes and plain javascript but i was only able to prevent the button's default reaction and stop the page from relaoding but i couldnt get the error-messages to show. i am aware that you have to get the error-messages display with javascript and run the php as backend script but i couldnt get it to work. i would appreciate any help.
here is my html form code:
<?php require('contact-script.php');
?>
<div class="container">
<form id="contact" action="index.php" method="POST">
<h3 id="test" >Contact Form</h3>
<h4>Contact us for custom quote</h4>
<span class="error" ><?php echo $errors['first']; ?></span>
<fieldset>
<input id="first" placeholder="First Name" name="first" type="text" value="<?php echo $first ?>" tabindex="1" >
</fieldset>
<span class="error" ><?php echo $errors['last']; ?></span>
<fieldset>
<input id="last" placeholder="Last Name" name="last" type="text" value="<?php echo $last ?>" tabindex="1" >
</fieldset>
<span class="error" ><?php echo $errors['mail']; ?></span>
<fieldset>
<input id="mail" placeholder="Your Email Address" name="mail" type="text" value="<?php echo $mail ?>" tabindex="2" >
</fieldset>
<span class="error" ><?php echo $errors['subject']; ?></span>
<fieldset>
<input id="subject" placeholder="Subject" name="subject" type="text" value="<?php echo $subject ?>" tabindex="2" >
</fieldset>
<fieldset>
<textarea id="message" placeholder="Type your message here...." name="message" type="text" value="<?php echo $message ?>" tabindex="5" ></textarea>
</fieldset>
<span class="error" ><?php echo $errors['message']; ?></span>
<fieldset>
<button id="formBtn" name="submit" type="submit" >Submit</button>
</fieldset>
</form>
</div>
here is my php code:
//defining Variables
$first = $last = $mail = $message = $subject = "";
$name_error = ""; $mail_error = ""; $message_error = "";
$errors = array( 'mail'=>'' , 'first'=> '' , 'last'=>'', 'subject'=>'', 'message'=>'');
if (isset($_POST['submit'])) {
$mail = htmlspecialchars($_POST['mail']);
$first = htmlspecialchars($_POST['first']);
$last = htmlspecialchars($_POST['last']);
$subject = htmlspecialchars($_POST['subject']);
$message = htmlspecialchars($_POST['message']);
//check mail
if (empty($_POST['mail'])) {
$errors['mail'] = 'Bitte geben Sie eine E-mail Adresse an <br />';
}
else {
$mail = $_POST['mail'];
if (!filter_var($mail, FILTER_VALIDATE_EMAIL)) {
$errors['mail'] = 'Bitte geben Sie eine gültige E-mail an';
}
}
//check first name
if(empty($_POST['first'])) {
$errors['first'] = 'Bitte geben Sie einen Namen an <br />';
}
else {
if(!preg_match('/^[a-zA-Z\s]+$/', $first)) {
$errors['first']= 'Name darf nur Buchstaben und Lehrzeichen enthalten ';
}
}
//check last name
if(empty($_POST['last'])) {
$errors['last'] = 'Bitte geben Sie einen Nachnamen an <br />';
}
else {
if(!preg_match('/^[a-zA-Z\s]+$/', $last)) {
$errors['last']= 'Name darf nur Buchstaben und Lehrzeichen enthalten';
}
}
if(empty($_POST['subject'])) {
$errors['subject'] = 'Bitte geben Sie ein Anliegen an <br />';
}
else {
if(!preg_match('/^[a-zA-Z\s]+$/', $subject)) {
$errors['subject']= 'Anliegen darf nur Buchstaben und Lehrzeichen enthalten ';
}
}
//check for message
if(empty($_POST['message'])) {
$errors['message']= 'Bitte schreiben Sie eine Nachricht <br />';
}
if (array_filter($errors)) {
}else {
$mailTo = "info#blanc-code.de";
$headers = "From: ".$mail;
$text = "Sie haben eine e-mail von ".$first." ".$last." erhalten.\n\n".$message;
mail($mailTo, $subject, $text, $headers);
}
i tryed this code for example:
function submitForm() {
getBtn = document.querySelector('#formBtn');
getBtn.disabled = true;
let formdata = new FormData();
formdata.append("mail", document.querySelector('mail').value);
formdata.append("first", document.querySelector('first').value);
formdata.append("last", document.querySelector('last').value);
formdata.append("subject", document.querySelector('subject').value);
let http = new XMLHttpRequest();
http.open("POST", "contact-script.php");
http.onreadystatechange = function() {
if(http.readyState == 4 && http.status == 200) {
if(http.responseText == "success") {
}else {
getBtn.disabled = false;
}
}
}
http.send(formdata);
or this:
$(document).ready(function(){
$("form").submit(function(event) {
event.preventDefault();
var first = $("#first").val();
var last = $("#last").val();
var mail = $("#mail").val();
var subject = $("#subject").val();
var message = $("#message").val();
$(".error").load("contact-script.php", {
first: first,
last: last,
mail: mail,
subject: subject,
message: message
});
});
});
there was more but this should give you a clue

Custom Form in WordPress Page Won't Submit/Refresh

I had a normal site that I built with custom HTML/CSS/JS. I changed the site to become a WordPress site (and made my custom html/css/js into a custom WordPress theme). I had a contact form on the homepage of the site, which broke when I made the change to WordPress.
When the form was functioning, it would refresh the page and bring the user back down to the form (using the anchor id=contactphilly) and then the user would see a message confirming their email was sent.
I did a LOT of Googling and I think it has something to do with the "action" option in the form, but no matter what I try changing it to, it doesn't work. I tried the following for the action value:
<?php the_permalink(); ?>/#contactphilly
#contactphilly
<?php echo htmlspecialchars($_SERVER['PHP_SELF']); ?>
$_SERVER['REQUEST_URI']
None of them worked.
Here is the code for the form:
<?php
if (isset($_POST["submit"])) {
$name = $_POST['name'];
$subject = $_POST['subject'];
$email = $_POST['email'];
$message = $_POST['message'];
$from = 'WebKeep.com';
$to = 'info#webkeepteam.com';
$subjectemail = 'Message from WebKeepTeam.com Contact Form ';
$body = "From: $name\n E-Mail: $email\n Subject: $subject\n Message:\n $message";
// Check if name has been entered
if (!$_POST['name']) {
$errName = 'Please enter your name';
}
// Check if email has been entered and is valid
if (!$_POST['email'] || !filter_var($_POST['email'], FILTER_VALIDATE_EMAIL)) {
$errEmail = 'Please enter a valid email address';
}
//Check if message has been entered
if (!$_POST['message']) {
$errMessage = 'Please enter your message';
}
// If there are no errors, send the email
if (!$errName && !$errEmail && !$errMessage) {
if (mail ($to, $subjectemail, $body, $from)) {
$result='<div>Thank You! We will respond shortly.</div>';
} else {
$result='<div>Sorry there was an error sending your message. Please try again later</div>';
}
}
}
?>
and
<form name="contactform" method="post" action="#contactphilly">
<div class="col-lg-6 col-md-6 col-sm-12 col-xs-12">
<fieldset class="form-group">
<input type="text" value="<?php echo $name;?>" class="form-control transparent-input" id="name" name="name" placeholder="Name">
</fieldset>
<?php echo "<p class='text-danger'>$errName</p>";?>
<fieldset class="form-group">
<input type="email" value="<?php echo $email;?>" class="form-control transparent-input" id="email" name="email" placeholder="Email">
</fieldset>
<?php echo "<p class='text-danger'>$errEmail</p>";?>
<fieldset class="form-group">
<input type="text" class="form-control transparent-input" value="<?php echo $subject;?>" id="subject" name="subject" placeholder="Subject">
</fieldset>
</div>
<div class="col-lg-6 col-md-6 col-sm-12 col-xs-12">
<fieldset class="form-group">
<textarea class="form-control transparent-input" id="message" value="<?php echo $message;?>" name="message" rows="6" placeholder="Message"><?php echo htmlspecialchars($_POST['message']);?></textarea>
</fieldset>
<?php echo "<p class='text-danger'>$errMessage</p>";?>
<input id="submit" name="submit" type="submit" value="Send" class="btn btn-index pull-right">
</div>
<?php echo $result; ?>
</form>
I found an answer to my own question! I completely forgot about this bit of code on GitHub: https://github.com/dwyl/html-form-send-email-via-google-script-without-server I used it elsewhere on the site and it worked, and it also works beautifully for forms within pages too!

Need to process a contact form

I purchased a theme, and I need to make a processing.php for my contact form. The form that sends the data to the server for processing.
This is the form code:
<div class="form_error text-center">
<div class="name_error hide error">Please Enter your name</div>
<div class="email_error hide error">Please Enter your Email</div>
<div class="email_val_error hide error">Please Enter a Valid Email Address</div>
<div class="message_error hide error">Please Enter Your Message</div>
</div>
<div class="Sucess"></div>
<form role="form">
<div class="row">
<div class="col-md-4">
<input type="text" class="form-control" id="name" placeholder="Name">
<input type="email" class="form-control" id="email" placeholder="Email">
<input type="text" class="form-control" id="subject" placeholder="Subject">
</div>
<div class="col-md-8">
<textarea class="form-control" id="message" rows="25" cols="10" placeholder=" Message Texts..."></textarea>
<button type="button" class="btn btn-default submit-btn form_submit">SEND MESSAGE</button>
</div>
</div>
</form>
Both shubham and adi's answers are vulnerable to SMTP header injections, allowing your contact form to be used to send spam. It will happen.
Any POST or GET data passed to the additional_headers parameter needs to be sanitised to prevent abuse.
See the following:
http://php.net/manual/en/function.mail.php
https://www.phpsecure.info/v2/article/MailHeadersInject.en.php
see this example
<?php
if(isset($_POST['submit'])){
$to = "email#example.com"; // this is your Email address
$from = $_POST['email']; // this is the sender's Email address
$first_name = $_POST['first_name'];
$last_name = $_POST['last_name'];
$subject = "Form submission";
$subject2 = "Copy of your form submission";
$message = $first_name . " " . $last_name . " wrote the following:" . "\n\n" . $_POST['message'];
$message2 = "Here is a copy of your message " . $first_name . "\n\n" . $_POST['message'];
$headers = "From:" . $from;
$headers2 = "From:" . $to;
mail($to,$subject,$message,$headers);
mail($from,$subject2,$message2,$headers2); // sends a copy of the message to the sender
echo "Mail Sent. Thank you " . $first_name . ", we will contact you shortly.";
// You can also use header('Location: thank_you.php'); to redirect to another page.
}
?>
<!DOCTYPE html>
<head>
<title>Form submission</title>
</head>
<body>
<form action="" method="post">
First Name: <input type="text" name="first_name"><br>
Last Name: <input type="text" name="last_name"><br>
Email: <input type="text" name="email"><br>
Message:<br><textarea rows="5" name="message" cols="30"></textarea><br>
<input type="submit" name="submit" value="Submit">
</form>
</body>
</html>
<?php
if (isset($_POST['contact_name'])&&isset($_POST['contact_mail'])&&isset($_POST['message'])) {
$contact_name = $_POST['contact_name'];
$contact_mail = $_POST['contact_mail'];
$message = $_POST['message'];
if (!empty($contact_name) && !empty($contact_mail) && !empty($message)) {
$to = 'your email#gmail.com'; // this is where you want to send the email
$subject = 'Contact form Submitted';
$body = $contact_name."\n".$message;
$headers = 'From:'.$contact_mail; // email of the sender
if (#mail($to, $subject, $body, $headers)) {
echo 'Thanks for contacting us';
}
else {
echo 'Sorry, an error has been occurred';
}
}
else {
echo 'All fields are required';
}
}
?>
<form action="index.php" method="POST">
Name:<br>
<input type="text" name="contact_name"></input><br><br>
Email Address:<br>
<input type="text" name="contact_mail"></input><br><br>
Message:<br>
<textarea name="message" cols="30" rows="6"></textarea><br><br>
<input type="submit" value="Send"></input>
</form>
maybe this codes can help you

Display custom error message in login

I want to implement a simple login with PHP. But, also I want to customize the error message when the login is incorrect, for example display a error message in red color.
Login.php
<form id="frmlogin" name="frmlogin" method="POST" action="validarUsuario.php">
<p><input type="text" name="usuario" id="usuario" class="required" maxlength="50" placeholder="Nombre Usuario"></p>
<p><input type="password" name="password" id="password" class="required" maxlength="50" placeholder="Password"></p>
<p id=error> </p>
<p class="submit"><input type="submit" name="commit" value="Login"></p>
</form>
validarUsuario.php
<?php
include("connection.php");
conectar_bd();
$usr = $_POST['usuario'];
$pw = md5($_POST['password']);
$sql = "SELECT usr FROM Client WHERE usr = '$usr'AND password ='$pw'";
$result = mysql_query($sql, $con);
if ($fila = mysql_fetch_array($result)) {
header('Location: menuclient.php');
} else {
/* How customize my message error */
}
?>
In the Login.php file, when the username or password are not correct, i want to display, for example, in id=error : "Login Incorrect" in red.
I dont know if I can do it with php.
Thanks for your help.
You can use session. Try following way.
Login.php
<?php
session_start();
if($_SESSON['error']): ?>
<span>Error : <?php echo $_SESSION['errorMsg']; ?></span>
<?php endif; ?>
<form id="frmlogin" name="frmlogin" method="POST" action="validarUsuario.php">
<p><input type="text" name="usuario" id="usuario" class="required" maxlength="50" placeholder="Nombre Usuario"></p>
<p><input type="password" name="password" id="password" class="required" maxlength="50" placeholder="Password"></p>
<p id=error> </p>
<p class="submit"><input type="submit" name="commit" value="Login"></p>
</form>
validarUsuario.php
<?php
session_start();
include("connection.php");
conectar_bd();
$usr = $_POST['usuario'];
$pw = md5($_POST['password']);
$sql = "SELECT usr FROM Client WHERE usr = '$usr'AND password ='$pw'";
$result=mysql_query($sql,$con);
if( $fila=mysql_fetch_array($result) )
{
header('Location: menuclient.php');
}
else {
$_SESSION['errorMsg'] = "Wrong username or Password";
$_SESSION['error'] = true;
header('Location: Login.php');
}
?>

How to make javascript contact form submit correctly

html code:
Contact Me
<label for="Name">Name:</label>
<input type="text" name="name" id="Name" accesskey="N" tabindex="1">
<label for="Email">E-mail:</label>
<input type="text" name="email" id="Email" accesskey="E" tabindex="1">
<label for="Phone">Phone Number:</label>
<input type="text" name="number" id="Number" tabindex="1">
<label for="Comment">Comments</label>
<textarea type="text" name="comment" id="Comment" rows="27" cols="70" tabindex="1"></textarea>
<input id="mySubmit" type="submit" value="Submit">
</form>
</fieldset>
</div>
email.php
<?php
if (isset($_POST['submit'])) {
$email = filter_input(INPUT_POST, 'email', FILTER_VALIDATE_EMAIL);
if (!$email)
echo "<script type='text/javascript'>alert('Please enter a valid email address...');history.back();</script>";
else {
$to = "randomemail#gmail.com"; //change this to YOUR email address
$name = (isset($_POST['name'])) ? $_POST['name'] : "anonymous";
$number = (isset($_POST['number'])) ? $_POST['number'] : "none";
$comment = (isset($_POST['comment'])) ? $_POST['comment'] : "none";
$subject = "Message from $name via contact form";
$message = "Name: $name\nNumber: $number\nEmail: $email\nMessage: $comment";
$from = "From: " . $name . "<" . $email .">\r\n" .
"Reply-To: " . $email ."\r\n" .
"X-Mailer: PHP/" . phpversion();
if (mail($to, $subject, $message, $from))
header("Location: thanks.html");
else
echo "<script type='text/javascript'>alert('An unknown system error has occurred!');history.back();</script>";
}
}
?>
when you submit, it loads email.php, but only a white page, not the thanks.html that it should.
You forgot to name your submit field:
<input id="mySubmit" type="submit" value="Submit" name="submit">
^^^^^^^^^^^^^
Don't use form fields to detect a post. Use the 100% reliable:
if ($_SERVER['REQUEST_METHOD'] == 'POST') { ... }
instead. This will ALWAYS be true if a POST was performed. As you can see with your version, a simple typo or oversight will completely kill your logic.
First Empty your file and just put header("Location: thanks.html"); in your php tags. If it works then add the other lines progressively. you'll see the annoying line. Read about header on PHP reference website. It should be used carefully

Categories

Resources