$error messate POST into div in index.php - javascript

This is my first question on this site however I have been here millions of times looking for answer and I hope you can help me out this time as I wasn't able to figure it out myself.
I am not very skilled when it comes to coding but was hoping to amend the php contact form I have found online (it's free), the form itself is worki9ng but what I am struggling with is to set the errors to be printed on the main page where the form is, at them moment the yare displayed on the contact.php form which is where the php code is and I would like it all displayed in a div for example on index.php just under the form.
my contact.php
<?php
if (isset($_POST['submit'])) {}
$sendTo = "email address";
$subject = "msg content";
$headers = 'From: email address' . "\r\n";
$name = #$_POST['name'];
$email = #$_POST['email'];
$message = #$_POST['message'];
$okMessage = 'thank you';
$errorMessage = 'Please fill all the fields';
$url = 'https://www.google.com/recaptcha/api/siteverify';
$privatekey = "----------------------------------------";
$response = file_get_contents($url."?secret=".$privatekey."&response=".$_POST['g-recaptcha-response']."&remoteip=".$_SERVER['REMOTE_ADDR']);
$data = json_decode($response);
$emailText = "Name: $name \n Email: $email \n Message: $message";
if (isset($data->success) AND $data->success==true) {
mail($sendTo, $subject, $emailText, $headers);
$responseArray = $okMessage;
}
else
{
//verification failed
$responseArray = $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;
}
?>
<form method="post" name="contactform" action="contact.php" >
<div class="field half first">
<label for="name">name</label>
<input type="text" name="name" id="name" placeholder="name" />
</div>
<div class="field half">
<label for="email">Email</label>
<input type="text" name="email" id="email" placeholder="email#email.com" />
</div>
<div class="field">
<label for="message">message</label>
<textarea name="message" id="msg" rows="4" placeholder="type your message here"></textarea>
</div>
<div class="g-recaptcha" data-sitekey="----------------------------------"></div>
<ul class="actions">
<li><input type="submit" value="send" class="special" /></li>
<li><input type="reset" value="reset pola" /></li>
</ul>
I have tried to use $_POST and $_GET to echo responseArray but I can't figure it out...
Is anyone able to provide a code I would have to use to display $okMessage and $errorMessage on index.php please?
Many thanks for all help

Related

Wordpress PHP Contact form - problem with displaying message about sent mail

I'm trying to develop a contact form for a language school website that runs on Wordpress.
Disclaimer: I'm about 6 months into coding, so please forgive me for being new to this. I'm developing my own theme and I wanted to limit usage of plugins to bare minimum for safety reasons - I prefer to learn how to write stuff myself instead on relying on updates of a third-party plus the courses I follow on Wordpress dev listed it as a good practice to avoid unnecessary plugins.
Update: I tried implementing plugins, but they either broke my page or didn't work anyway.
The problem is listed below in bold.
What I want to achieve:
Simple contact form that takes following info: name, email, course, phone (optional) and a message.
Validate the form if user provided correct info - I can't make the
user provide valid info, but at least I want to lock number into
numbers only range and check if email is correct.
Check if user is human (Captcha).
Send the email to my address and provide a copy to the sender.
Inform the user whether the action was a success or a failure.
What I succeeded with:
Mail gets sent.
Captacha seems to be working and filtering out attempts that do not click on it.
What 'kinda works':
The PHP doesn't seem to validate the form. I used HTML type and require instead, but I've read that solution is not ideal. I tried to use JS to write some functions that would prevent unwanted input, but I couldn't get it to work properly. I decided to ask the question first in case it might be a dead end. JS seems to be working on my Wordpress as I'm using Bootstrap and some custom JS for certain features so I'm pretty sure the code gets executed, but I wanted to ask first if that's the correct way of approach it before I invest my time in it.
What I have a problem with:
It is imperative to me that the user gets feedback from the page whether the email has been sent or not for obvious business-client communication reasons. I tried two solutions found on SO:
Injecting JS alert into PHP's echo inside conditional (JS doesn't get executed)
Using header method to redirect into thank-you.page that informs about success or error.page that
informs about a failure and recommends another avenue of contact
What went wrong: the second solution got executed properly, the user gets redirected to site.com/thank-you or site.com/error, however the browser crashes due to 'too many redirects'.
I tried googling, I tried different solutions from tutorials. What would be your recommendation?
My code:
<?php
$nameErr = $emailErr = $courseErr = $phoneErr = "";
$name = $email = $course = $comment = $phone = "";
$thank_you = wp_redirect( '"'.home_url().'/thank-you"', 301 );
$error = wp_redirect( '"'.home_url().'/error', 301 );
if ($_SERVER["REQUEST_METHOD"] == "POST") {
if (empty($_POST["name"])) {
$nameErr = "Give name";
} else {
$name = test_input($_POST["name"]);
// check if name only contains letters and whitespace
if (!preg_match("/^[a-zA-Z-' ]*$/",$name)) {
$nameErr = "Only letters allowed";
}
}
if (empty($_POST["email"])) {
$emailErr = "Need email";
} else {
$email = test_input($_POST["email"]);
// check if e-mail address is well-formed
if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
$emailErr = "Email incorrect";
}
}
if (empty($_POST["phone"])) {
$phone = "";
} else {
$phone = test_input($_POST["phone"]);
// check if URL address syntax is valid (this regular expression also allows dashes in the URL)
if (!is_numeric($number)) {
$phoneErr = "Bad number";
}
}
if (empty($_POST["comment"])) {
$comment = "";
} else {
$comment = test_input($_POST["comment"]);
}
if (empty($_POST["course"])) {
$courseErr = "Pick course";
} else {
$course = test_input($_POST["course"]);
}
}
function test_input($data) {
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
if(!empty($_POST['g-recaptcha-response']))
{
$secret = 'mySecretKey';
$verifyResponse = file_get_contents('https://www.google.com/recaptcha/api/siteverify?secret='.$secret.'&response='.$_POST['g-recaptcha-response']);
$responseData = json_decode($verifyResponse);
if($responseData->success)
$message = "g-recaptcha verified successfully";
if(isset($_POST['submit'])){
$to = "myEmail#mail.org"; // this is your Email address
$from = $_POST['email']; // this is the sender's Email address
$name = $_POST['name'];
$course = $_POST['course'];
$phone = $_POST['phone'];
$comment = "Form submission";
$comment2 = "Copy of your form submission";
$message = "Name:" . $name . "Interested in " . $course. " Number" . $phone . " " . " Wrote" . "\n\n" . $_POST['comment'];
$message2 = "Copy " . $name ."\n\n" . "Interested in:" . $course . "\n\n" . $_POST['comment'];
$headers = "From:" . $from;
$headers2 = "From:" . $to;
mail($to,$comment,$message,$headers);
mail($from,$comment2,$message2,$headers2);
// sends a copy of the message to the sender
header($thank_you);
// This redirects to page thanking for contact.
}
else
header($error);
// This redirects to page informing about failure.
$message = "couldn't verify Captcha. Email not sent.";
echo '<script type="text/javascript">mailNotSent();</script>';
}
?>
<section id="contact" class="contact">
<div class="container pseudonest">
<div class="pseudonest contact__head--nest">
<h1 class="display-5 lh-1 mb-2 contact__head--pseudocircle contact__head--header mx-auto">Enroll now</h1>
</div>
<div class="container m-auto">
<div class="d-flex justify-content-center contact__form">
<div class="col-md-7 col-lg-8">
<form action="" method="post">
<form class="needs-validation" novalidate>
<div class="row g-3">
<div class="col">
<label for="name" id="nameHeader" class="form-label">Name</label>
<input type="text" class="form-control radio__margin" id="name" name="name"
placeholder="" value="<?php echo $name;?>" required>
<div class="invalid-feedback">
<?php echo $nameErr;?>
</div>
<label for="email" class="form-label">Email</label></label>
<input type="email" class="form-control radio__margin" id="email" name="email"
placeholder="you#example.com" value="<?php echo $email;?>" required>
<div class="invalid-feedback">
<?php echo $emailErr;?>
</div>
<label for="phone" class="form-label">Phone</label></label>
<input type="number" class="form-control radio__margin" id="phone" name="phone"
pattern="[0-9]+" placeholder="+48 111 222 333" value="<?php echo $phone;?>">
<div class="invalid-feedback">
<?php echo $phoneErr;?>
</div>
</div>
<div class="col radio__col">
<label for="firstName" class="form-label">Course?</label>
<div class="row radio__section">
<label class="radio__container">English
<input type="radio" name="course"
<?php if (isset($course) && $course=="English") echo "checked";?>
value="English">
<span class="radio__checkmark"></span>
</label>
<label class="radio__container">
<input type="radio" name="course"
<?php if (isset($course) && $course=="Polish") echo "checked";?>
value="Polish">
<span class="radio__checkmark"></span>Polish
</label>
<label class="radio__container">
<input type="radio" name="course"
<?php if (isset($course) && $course=="Italian") echo "checked";?>
value="Italian">
<span class="radio__checkmark"></span>Italian
</label>
<span class="error"> <?php echo $courseErr;?></span>
</div>
</div>
</div>
<div class="col-12 mb-5">
<label for="email-content" class="form-label">Content</label>
<div class="input-group has-validation">
<textarea class="form-control" rows="5" name="comment"
cols="30"><?php echo $comment;?></textarea>
<div class="invalid-feedback">
</div>
</div>
</div>
<form id="frmContact" action="varify_captcha.php" method="POST" novalidate="novalidate">
<div class="g-recaptcha my-3" data-sitekey="mySiteKey">
</div>
<input type="submit" name="submit" value="Send" id="submit"
class="btn btn-primary contact__form--btn">
<div id="fakeSubmit" class="btn btn-primary contact__form--btn hidden">Fill the form
</div>
</form>
</form>
</div>
</div>
</section>

How to show success message below html form after form submit which is being handled by different php file

There is a form in my index.php file. This form is handling from a different php file named send-mail.php. I want to show a message inside alert div in index.php file. Can this be done by php or javascript will be needed too?
index.php:
<section id="contact">
<form action="send-mail.php" id="form" method="post" name="form">
<input id="name" name="name" placeholder="your name" type="text" required>
<input id="email" name="email" placeholder="your e-mail" type="email" required>
<textarea cols="50" id="message" name="message" placeholder="your enquiry" rows="4" required></textarea>
<input type="submit" name="submit" id="submit" value="Send Message">
</form>
<div class="alert alert-dismissible fade in hide" role=alert>
<button type=button class=close data-dismiss=alert aria-label=Close><span aria-hidden=true>×</span></button>
</div>
</section>
send-mail.php:
<?php
if(isset($_POST['submit'])){
// Get the submitted form data
$name = $_POST['name'];
$email = $_POST['email'];
$message = $_POST['message'];
// Recipient email
$toEmail = 'user#example.com';
$emailSubject = 'Contact Request Submitted by '.$name;
$htmlContent = '<h2>Contact Request Submitted</h2>
<h4>Name</h4><p>'.$name.'</p>
<h4>Email</h4><p>'.$email.'</p>
<h4>Message</h4><p>'.$message.'</p>';
// Set content-type header for sending HTML email
$headers = "MIME-Version: 1.0" . "\r\n";
$headers .= "Content-type:text/html;charset=UTF-8" . "\r\n";
// Additional headers
$headers .= 'From: '.$name.'<'.$email.'>'. "\r\n";
// Send email
if(mail($toEmail,$emailSubject,$htmlContent,$headers)){
$statusMsg = 'Your contact request has been submitted successfully !';
$msgClass = 'alert-success';
header('location: index.php#contact');
}else{
$statusMsg = 'Your contact request submission failed, please try again.';
$msgClass = 'alert-danger';
header('location: index.php#contact');
}
}
?>
Change your redirects to:
header('location: index.php?result='.$msgClass.'#contact');
Then adding the following to your index.php file:
if ($_GET['result']=="alert-success") {
// display success message here
} elseif ($_GET['result']=="alert-danger") {
// display error message here
}

Show thank you message after form is submitted after PHP validation

I have looked at a few solutions on here trying different ways of doing this but none are working for me.
Here is my form:
<form action="<?PHP echo htmlspecialchars($_SERVER['PHP_SELF']); ?>" method="POST" name="contact" role="form">
<?PHP //if error has occured then echo the error in red
if(isset($errorMsg) && $errorMsg) {
echo "<p style=\"color: red;\">*",htmlspecialchars($errorMsg),"</p>\n\n";
}
?>
<label for="name"><b>Name:</b></label>
<input type="text" name="name" id="name" placeholder="Enter full name" value="<?PHP if(isset($_POST['name'])) echo htmlspecialchars($_POST['name']); ?>">
<label for="email"><b>Email:</b></label>
<input type="text" name="email" id="email" placeholder="Enter a valid email address..." value="<?PHP if(isset($_POST['email'])) echo htmlspecialchars($_POST['email']); ?>">
<label><b>Subject:</b></label>
<input type="text" name="subject" id="subject" placeholder="Please enter a subject matter" value="<?PHP if(isset($_POST['subject'])) echo htmlspecialchars($_POST['subject']); ?>">
<label for="query"><b>Query:</b></label>
<textarea id="query" placeholder="Please write your message here..." name="query" value="<?PHP if(isset($_POST['query']))echo htmlspecialchars($_POST['query']);?>">
</textarea>
<input type="submit" name="submit" id="submit" value="Submit" class="style-button">
</form>
I am using a one page website so the contact form is at the bottom of the page.
How can i show a thank you message inside the form when it has been submitted and went through validation - without the page going back to the top?
PHP code:
<?php
// if submit is clicked then assign variables
if($_POST && isset($_POST['submit'], $_POST['name'], $_POST['email'], $_POST['subject'], $_POST['query'])) {
$name = $_POST['name'];
$email = $_POST['email'];
$subject = $_POST['subject'];
$query = $_POST['query'];
//making sure the page goes to the contact form with the errors instead of the top of the page
if(!isset($_POST['$errorMsg']))
{
?>
<script>
window.location.hash = '#contact-form';
</script>
<?php
}
// if name is not entered then display errorMsg
if (!$name) {
$errorMsg = "Please enter your name";
}
// if email is not entered then display errorMsg
elseif (!$email || !preg_match("/^\S+#\S+$/", $email)) {
$errorMsg = "Please enter a valid email address";
}
// If the subject has not entered then display errorMsg
elseif (!$subject) {
$errorMsg = "Please enter a subject";
}
// if query is not entered then display errorMsg
elseif (!$query) {
$errorMsg = "Please enter your query";
}
else {
//send email and redirect to confirmation page
$toemail = "email#example.com";
$subject2 = "Message recieved from ". $name."";
$headers = "MIME-Version: 1.0\n"
."From: \"".$name."\" <".$email.">\n"
."Content-type: text/html; charset-iso-8859-1\n";
$body = "Email: ".$email."<br>\n"
."Subject: ".$subject."<br>\n"
."email: ".$email."<br>\n"
."query: ".$query."<br>\n"
;
mail($toemail, $subject, $body, $headers);
if(mail($toemail, $subject, $body, $headers)){
$toemail =".$email";
$subject = "Confirmation Email";
$body = "Your email has been sent";
header("location: index.php");
}
}}
?>
Somewhere, hopefully above the HTML, you are processing the form post. So you should be setting $errorMsg in there.
Rule of thumb for a self-submitting web page: logic before view. Also, to avoid the if() statement, initialize $errorMsg on every page load.

php mail with .js validation -> can't see any mistakes

I got this piece of code from a free template and I followed all the instructions that came with it, everything seems fine but mail doesn't go trough.
HTML:
<!--Start Contact form -->
<form name="enq" method="post" action="email/" onsubmit="return validation();">
<fieldset>
<input type="text" name="name" id="name" value="" class="input-block-level" placeholder="Name.." />
<input type="text" name="email" id="email" value="" class="input-block-level" placeholder="Email.." />
<textarea rows="11" name="message" id="message" class="input-block-level" placeholder="Message.."></textarea>
<div class="actions">
<input type="submit" value="Send!" name="submit" id="submitButton" class="btn btn-info pull-right" title="Send!" />
</div>
</fieldset>
</form>
<!--End Contact form -->
PHP
<?php
if(isset($_POST['submit']))
{
$name = $_POST['name'];
$email = $_POST['email'];
$query = $_POST['message'];
$email_from = $name.'<'.$email.'>';
$to="email#sample.com";
$subject="Enquiry!";
$headers = 'MIME-Version: 1.0' . "\r\n";
$headers .= 'Content-type: text/html; charset=iso-8859-1' . "\r\n";
$headers .= "From: ".$email_from."\r\n";
$message="
Name:
$name
<br>
Email-Id:
$email
<br>
Message:
$query
";
if(mail($to,$subject,$message,$headers))
header("Location:../contact.php?msg=Successful Submission! Thankyou for contacting us.");
else
header("Location:../contact.php?msg=Error To send Email !");
//contact:-your-email#your-domain.com
}
?>
JavaScript
function validation()
{
var contactname=document.enq.name.value;
var name_exp=/^[A-Za-z\s]+$/;
if(contactname=='')
{
alert("Name Field Should Not Be Empty!");
document.enq.name.focus();
return false;
}
else if(!contactname.match(name_exp))
{
alert("Invalid Name field!");
document.enq.name.focus();
return false;
}
var email=document.enq.email.value;
//var email_exp=/^[A-Za-z0-9\.-_\$]+#[A-Za-z]+\.[a-z]{2,4}$/;
var email_exp=/^\w+([-+.']\w+)*#\w+([-.]\w+)*\.\w+([-.]\w+)*$/;
if(email=='')
{
alert("Please Enter Email-Id!");
document.enq.email.focus();
return false;
}
else if(!email.match(email_exp))
{
alert("Invalid Email ID !");
document.enq.email.focus();
return false;
}
var message=document.enq.message.value;
if(message=='')
{
alert("Query Field Should Not Be Empty!");
document.enq.message.focus();
return false;
}
return true;
}
I don't get any errors but mail doesn't simply go trough, checked spam etc.
I hope you changed
$to="email#sample.com";
to your actual e-mail.. I can't see anything else.
Seems it was due to webhost(mailserver). Works like a charm on another webhost.

How do I force form submit with Jquery

Wish you all a happy 2015!
I have a simple contact us php form. I am validating it with parsley.js. The validation works fine but I am receiving a lot of spam mails.
I believe if I can force the form to be submitted only if Jquery is enabled, then it should solve my problem (right?).
I'm not an expert with PhP/ Jquery and any help will be appreciated.
Here is my PHP code
<?php
// Define Variables i.e. name tag, as per form and set to empty
$contact_name = $contact_email = $contact_phone = $contact_message = "";
// Sanitize data and use friendly names
if ($_SERVER["REQUEST_METHOD"] == "POST") {
$name = test_input($_POST["contact_name"]);
$email = test_input($_POST["contact_email"]);
$phone = test_input($_POST["contact_phone"]);
$message = test_input($_POST["contact_message"]);
}
function test_input($data) {
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
// Set values
$to = 'info#foryourservice.in';
$subject = 'New Message from Website';
$headers = 'From: info#domainname.com' . "\r\n" .
'Reply-To: info#domainname.com' . "\r\n" .
'X-Mailer: PHP/' . phpversion();
// Set Email content
$emailcontent = "A new message has been submitted from the website.
\n
Name : $name
Email : $email
Phone : $phone
Message : $message";
// Mail function
$send_contact=mail($to,$subject,$emailcontent,$headers);
if($send_contact){
header('Location: index.php#contactusform');
}
else {
echo "<script type='text/javascript'>alert('We encountered an ERROR! Please go back and try again.');</script>";
}
?>
Here is my HTML ( Im using Twitter Bootstrap)
<form role="form" method="POST" action="contactusform.php" id="contactusform" data-parsley-validate>
<div class="col-xs-6">
<div class="form-group" style="margin-bottom: -5px">
<label for="input1"></label>
<input type="text" name="contact_name" class="form-control" id="input1" placeholder="Name*" required data-parsley-required-message="Please enter your name">
</div>
<div class="form-group" style="margin-bottom: -5px">
<label for="input2"></label>
<input type="email" name="contact_email" class="form-control" id="input2" placeholder="Email Address*" data-parsley-trigger="change" required data-parsley-required-message="Please enter a valid Email address">
</div>
<div class="form-group" style="margin-bottom: -5px">
<label for="input3"></label>
<input type="tel" name="contact_phone" class="form-control" id="input3" placeholder="Phone Number*" required data-parsley-type="digits" data-parsley-minlength="10" data-parsley-maxlength="10" data-parsley-required-message="Please enter a 10 digit number">
</div>
<br>
<div class="form-group">
<button type="submit" id="contactbutton" class="btn btn-primary" style="background-color: #A8B645; border-color: transparent">Submit</button>
</div>
</div>
<div class="col-xs-6">
<div class="form-group">
<label for="input4"></label>
<textarea name="contact_message" class="form-control" rows="7" id="input4" placeholder="Message*" required required data-parsley-required-message="Say something!"></textarea>
</div>
</div>
</form>
This is what the Spam Email looks like :
A new message has been submitted from the website.
Name : お買い得アナスイ ミロード大壳り出しランキング
Email : rsilau#gmail.com
Phone : お買い得アナスイ ミロード大壳り出しランキング
Message : Shoppers takes the boast on bag
お買い得アナスイ ミロード大壳り出しランキング http://www.frkapaun.org/dyqfmnwg/ysl-annasuixmraAekm.asp
Add a hidden field to your form:
<input type="hidden" value="0" id="botcheck" name="botcheck" />
Then with jQuery set the value to 1:
$("#botcheck").val("1");
Then server-side check the value of $_POST["botcheck"].
You might want to check if your form is submitted using ajax:
if(!empty($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest') {
//Process form here
}
For further explanation

Categories