I am using bootstrap to create input fields. When someone clicks the "Submit" button I want the values (if they are valid) to be emailed to myself. I am having trouble even making sure they are valid. Below is my code
<form action="tryjs_submitpage.htm" onsubmit="return myFunction()">
<fieldset class="form-group">
<label for="name">Name*:</label>
<input type="text" class="form-control" id="usr" placeholder="Name">
</fieldset>
<fieldset class="form-group">
<label for="email">Email Address*:</label>
<input type="text" class="form-control" id="exampleInputEmail1" placeholder="Email">
</fieldset>
<fieldset class="form-group">
<label for="company">Company:</label>
<input type="text" class="form-control" id="company" placeholder="Company Name">
</fieldset>
<fieldset class="form-group">
<label for="message">Message*:</label>
<textarea class="form-control" rows="5" id="message" placeholder="Message"></textarea>
</fieldset>
<button type="submit" class="btn btn-primary">Submit</button>
</form>
<script>
function myFunction() {
var name = document.getElementById("Name").value;
var email = document.getElementById("Email").value.indexOf("#");
var company = document.getElementById("company").value;
var message = document.getElementById("message").value;
submitOK = "true";
if (name.length == 0) {
alert("You must enter your name");
submitOK = "false";
}
if (email == -1) {
alert("Not a valid e-mail!");
submitOK = "false";
}
if (message.length == 0) {
alert("You must enter a message");
submitOK = "false";
}
if (submitOK == "false") {
return false;
}
}
</script>
I modified the script from here, but when I click submit it says tryjs_submitpage.htm doesn't exist. Obviously this is an issue, but I can't seem to find tryjs_submitpage.htm anywhere to get it to work. Further I wanted to know if there was a way to trigger an email send with the appropriate information to my personal email. Thanks for the help!
You can't send an email directly with javascript for security reasons.
Suppose there is a feature in JavaScript to send email. Some malicious coder can write a script to send email to some address immediately when you visit their page. This will reveal your email address to some third party without your knowledge. They will start filling your mail box with lots of spam messages! However, there are alternatives as explained below. link
You can however open the user's mail client, to do so:
<form action="" onsubmit="sendMail(); return false">
...
...
<button type="submit" class="btn btn-primary">Submit</button>
</form>
<script>
function sendMail() {
var link = "mailto:me#abc.com"
+ "?cc=myCCaddress#example.com"
+ "&subject=" + escape("This is my subject")
+ "&body=" + escape(document.getElementById('myText').value)
;
window.location.href = link;
}
</script>
You can't send a mail directly from the browser, however you can use third party technologies like http://www.emailjs.com/ or create a .php file using php native mail function to send mail.
Below is the HTML, JS(Jquery AJAX) and PHP file that handles mail sending.
In this case the PHP script handles email verification, but you can also use HTML require or JS regex to check at the client side before sending a POST request to the server
HTML
<form method="POST" action="" id="contactform">
<p>
<label for="name">Your Name</label>
<input type="text" name="name" class="input" >
</p>
<p>
<label for="email">Your Email</label>
<input type="text" name="email" class="input">
</p>
<p>
<label for="message">Your Message</label>
<textarea name="message" cols="88" rows="6" class="textarea" ></textarea>
</p>
<input type="submit" name="submit" value="Send your message" class="button transition">
</form>
JS (JQuery)
var $contactform = $('#contactform'),
$success = 'Your message has been sent. Thank you!',
$url = 'link to the hosted php script';
$contactform.submit(function(e) {
$.ajax({
type: 'POST',
url: $url,
data: $(this).serialize(),
dataType: "json",
xhrFields: {
withCredentials: true
}
})
.done(function(msg) {
console.log(msg)
if (msg.success == true) {
response = '<div class="success">' + $success + '</div>';
}
else {
response = '<div class="error">' + msg.errors + '</div>';
}
// Hide any previous response text.
$('.error, .success').remove();
// Show response message.
$contactform.prepend(response);
})
.fail(function(msg) {
console.log(msg)
});
e.preventDefault();
});
PHP
<?php
// Array to hold validation errors and response data.
$errors = array();
$data = array();
// Validate the variables
// if any of these variables don't exist, add an error to our $errors array
$name = $_POST['name'];
$email = $_POST['email'];
$msg = $_POST['message'];
$nospace_name = trim($_POST['name']);
$nospace_email = trim($_POST['email']);
$nospace_message = trim($_POST['message']);
// * wont work in FF w/ Allow-Credentials
//if you dont need Allow-Credentials, * seems to work
header('Access-Control-Allow-Origin: *');
//if you need cookies or login etc
header('Access-Control-Allow-Credentials: true');
if ($this->getRequestMethod() == 'POST') {
header('Access-Control-Allow-Methods: GET, POST, PUT, DELETE, OPTIONS');
header('Access-Control-Max-Age: 604800');
//if you need special headers
header('Access-Control-Allow-Headers: x-requested-with');
}
if (empty($nospace_name))
$errors['name'] = "Name field is required.";
if (empty($nospace_email))
$errors['email'] = "Email field is required.";
if (empty($nospace_message))
$errors['message'] = "I would love to see your message.";
if (!empty($nospace_email) && !preg_match("^[a-zA-Z0-9_\-\.]+#[a-zA-Z0-9\-]+\.[a-zA-Z0-9\-\.]+$^", $nospace_email))
$errors['bad_email'] = "Please enter a valid email address";
// if there are any errors in our errors array, return a success boolean of false
if (!empty($errors)) {
// if there are items in our errors array, return those errors
$data['success'] = false;
$data['errors'] = $errors;
}
else {
// if there are no errors process our form, then return a message
// prepare message to be sent
$to = "admin#example.com";
$subject = "Website Contact Form: ".$name;
$headers = "From: noreply#example.com\n"; // email address the generated message will be from. Recommend using something like noreply#yourdomain.com.
$headers .= "Reply-To: ".$email;
// build the message
$message = "Name: ".$name."\n\n";
$message .= "Email: ".$email."\n\n";
$message .= "Message: ".$msg;
// send it
$mailSent = mail($to, $subject, $message, $headers);
// check if mail was sent successfully
if (!$mailSent) {
$errors['unknown_error'] = "Something went wrong...Please try again later";
$data['success'] = false;
$data['errors'] = $errors;
}
else {
// show a message of success and provide a true success variable
$data['success'] = true;
$data['message'] = "Thank you for contacting me, I\'ll get back to you soon!";
}
}
// return all our data to an AJAX call
echo json_encode($data);
?>
My advice is don't do the form validation yourself, just let the browser do it. You will need to change the input type on your email input to email, and you will need to add the required attribute to every one you want to be required.
This way instead of using JavaScript you can just use standards-compliant HTML.
Then, since you can't send email directly from the browser, you need a third-party service to send the email, like for example Formspree. Alternatively you could write a server-side script for sending email, but it's much easier to just use a service.
Here is the final code:
<form action="https://formspree.io/your.email.here#example.com">
<fieldset class="form-group">
<label for="usr">Name*:</label>
<input type="text" class="form-control" id="usr" placeholder="Name" name="message" required="required">
</fieldset>
<fieldset class="form-group">
<label for="exampleInputEmail1">Email Address*:</label>
<input type="email" class="form-control" id="exampleInputEmail1" placeholder="Email" name="email" required="required">
</fieldset>
<fieldset class="form-group">
<label for="message">Message*:</label>
<textarea class="form-control" rows="5" id="message" placeholder="Message" name="message" required="required"></textarea>
</fieldset>
<button type="submit" class="btn btn-primary">Submit</button>
</form>
If you want to use Formspree and also have your visitors enter their company name, you can hack it by giving the company name field a name of "subject", which Formspree will forward to your email alongside the rest of the fields.
You have a little mistake in your code,
parameter document.getElementById is element id :
change code :
var name = document.getElementById("Name").value;
var email = document.getElementById("Email").value.indexOf("#");
var company = document.getElementById("company").value;
var message = document.getElementById("message").value;
TO this :
var name = document.getElementById("usr").value;
var email = document.getElementById("exampleInputEmail1").value.indexOf("#");
var company = document.getElementById("company").value;
var message = document.getElementById("message").value;
Related
I should solve a problem with a contact form and I don't know where to put my hands anymore.
I have a form in HTML, then a validation in JS and finally an email sending in PHP.
The form data are: Name, Clinic, Email, Phone, Address and Valutation.
In the email I receive the data are:
Name: name entered in the form
Email: email entered in the form
Clinic: undefined
Phone: undefined
Address: undefined
Valutation: undefined
This is the code (HTML + JS):
// JavaScript Document
$(document).ready(function() {
"use strict";
$(".contact-form").submit(function(e) {
e.preventDefault();
var name = $(".name");
var email = $(".email");
var clinic = $(".clinic");
var phone = $(".phone");
var address = $(".address");
var valutation = $(".valutation");
var subject = $(".subject");
var msg = $(".message");
var flag = false;
if (name.val() == "") {
name.closest(".form-control").addClass("error");
name.focus();
flag = false;
return false;
} else {
name.closest(".form-control").removeClass("error").addClass("success");
}
if (email.val() == "") {
email.closest(".form-control").addClass("error");
email.focus();
flag = false;
return false;
} else {
email.closest(".form-control").removeClass("error").addClass("success");
}
var dataString = "name=" + name.val() + "&email=" + email.val() + "&subject=" + subject.val() + "&msg=" + msg.val() + "&clinic=" + clinic.val() + "&phone=" + phone.val() + "&address=" + address.val() + "&valutation=" + valutation.val();
$(".loading").fadeIn("slow").html("Loading...");
$.ajax({
type: "POST",
data: dataString,
url: "php/contactForm.php",
cache: false,
success: function(d) {
$(".form-control").removeClass("success");
if (d == 'success') // Message Sent? Show the 'Thank You' message and hide the form
$('.loading').fadeIn('slow').html('<font color="#48af4b">Mail sent Successfully.</font>').delay(3000).fadeOut('slow');
else
$('.loading').fadeIn('slow').html('<font color="#ff5607">Mail not sent.</font>').delay(3000).fadeOut('slow');
}
});
return false;
});
$("#reset").on('click', function() {
$(".form-control").removeClass("success").removeClass("error");
});
})
<div class="row justify-content-center">
<div class="col-lg-10 col-xl-8">
<div class="form-holder">
<form class="row contact-form" method="POST" action="php/contactForm.php" id="contactForm">
<!-- Form Select -->
<div class="col-md-12 input-subject">
<p class="p-lg">This question is about: </p>
<span>How satisfied are you with the service that Lab offers? </span>
<select class="form-select subject" aria-label="Default select example" name="valutation">
<option>Very unsatisfied</option>
<option>Unsatisfied</option>
<option>Satisfied</option>
<option>Very satisfied</option>
<option selected>I don't have an opinion</option>
</select>
</div>
<!-- Contact Form Input -->
<div class="col-md-12">
<p class="p-lg">Your Name: </p>
<span>Please enter your Dentist Name: </span>
<input type="text" name="name" class="form-control name" placeholder="Your Name*">
</div>
<div class="col-md-12">
<p class="p-lg">Clinic Name: </p>
<span>Please enter your Clinic Name: </span>
<input type="text" name="clinic" class="form-control name" placeholder="Clinic Name*">
</div>
<div class="col-md-12">
<p class="p-lg">Your Email Address: </p>
<span>Please carefully check your email address for accuracy</span>
<input type="text" name="email" class="form-control email" placeholder="Email Address*">
</div>
<div class="col-md-12">
<p class="p-lg">Phone Number: </p>
<span>Please enter your/clinic phone number: </span>
<input type="text" name="phone" class="form-control name" placeholder="Phone Number*">
</div>
<div class="col-md-12">
<p class="p-lg">Address: </p>
<span>Please enter Clinic Address: </span>
<input type="text" name="address" class="form-control name" placeholder="Address*">
</div>
<!-- Contact Form Button -->
<div class="col-md-12 mt-15 form-btn text-right">
<button type="submit" class="btn btn-skyblue tra-grey-hover submit">Submit Request</button>
</div>
<!-- Contact Form Message -->
<div class="col-lg-12 contact-form-msg">
<span class="loading"></span>
</div>
</form>
</div>
</div>
</div>
And this is the PHP code:
<?php
$name = $_REQUEST["name"];
$email = $_REQUEST["email"];
$clinic = $_REQUEST["clinic"];
$phone = $_REQUEST["phone"];
$address = $_REQUEST["address"];
$valutation = $_REQUEST["valutation"];
$to = "myemail#email.com";
if (isset($email) && isset($name)) {
$email_subject = "Request to access to the Price List";
$headers = "MIME-Version: 1.0" . "\r\n";
$headers .= "Content-type:text/html;charset=iso-8859-1" . "\r\n";
$headers .= "From: ".$name." <".$email.">\r\n"."Reply-To: ".$email."\r\n" ;
$msg = "From: $name<br/> Email: $email <br/> Clinic: $clinic <br/> Phone: $phone <br/> Address: $address <br/> Valutation: $valutation";
$mail = mail($to, $email_subject, $msg, $headers);
if ($mail) {
echo 'success';
} else {
echo 'failed';
}
}
?>
Your issue is your selectors. You only use classes name and email for all your inputs.
<input type="text" name="phone" class="form-control name" ...>
should actually be:
<input type="text" name="phone" class="form-control phone" ...>
and so on for all the other inputs. Change your selectors to the appropriate classNames.
Also, never just use i.e: $(".name");, $(".email"); etc. as your selectors. As you know already $(".name"); will get every class="name" in your document. Same goes for all the other selectors. Instead, use the second argument (ParentElement) that will limit the search only to the children elements of the provided parent:
var name = $(".name", this);
or rather, use attribute selectors like:
var clinic = $(`[name="clinic"]`, this);
IMPORTANT NOTE about validation:
never trust the client.
JS validation should be used minimally, just as a UX tool to help, inform the user about basic errors/typos. The real validation, as well as all the related error responses, should be handled on the backend side.
Currently your PHP seems quite open to XSS attacks.
You don't need a HTML <form> in order to send data to the server. All it takes to an attacker is to find your route/path (usually exposed via the form's action attribute), take a look at the names in the source and manually construct a HTTP request, and send dangerous arbitrary data to your server. Just so you keep in mind.
I am building a basic contact form (three fields) for my site. I have the form built in HTML and CSS; all I had to do was build the PHP to make the form responses send to my email. I found a tutorial and built the PHP file (which worked), but wanted the form to submit in the background and not leave the original page. I found an online tutorial to do that using Ajax, and after some tweaking, I got it mostly to work. The only issue I'm having now is that when I receive the email with the response, the message field is coming back as "undefined."
I have a good grasp on HTML and CSS, but PHP and JS are new to me (just started learning them for this project), so any help on how to fix this issue and possibly correct any wrong code would be a huge help. I've included the form HTML, PHP, and JS below (PHP and JS are both named 'contact.[filetype]'.
HTML
<div id="contact_form">
<form name="contact" action="">
<div class="field">
<label for="name">Name</label>
<input type="text" name="name" id="name" required/>
</div>
<div class="field">
<label for="email">Email</label>
<input type="text" name="email" id="email" required/>
</div>
<div class="field">
<label for="comments">Comments</label>
<textarea name="comments" id="comments" rows="3"></textarea>
</div>
<ul class="actions">
<li><input type="submit" name="submit" class="button" id="submit_btn" value="Send Message" /></li>
</ul>
</form>
</div>
PHP
<?php
$name = $_POST['name'];
$email = $_POST['email'];
$comments = $_POST['comments'];
$formcontent="From: $name \n Message: $comments \n";
$recipient = "alltheladsmedia#gmail.com";
$subject = "Message From Website";
$mailheader = "From: $email \r\n";
mail($recipient, $subject, $formcontent, $mailheader) or die("Error!");
echo "Thank You!" . " -" . "<a href='index.html' target='_blank' style='text-decoration:none;color:#505050;'> Return Home</a>";
?>
JS
$(function() {
$('.error').hide();
$(".button").click(function() {
// validate and process form here
$('.error').hide();
var name = $("input#name").val();
if (name === "") {
$("label#name_error").show();
$("input#name").focus();
return false;
}
var email = $("input#email").val();
if (email === "") {
$("label#email_error").show();
$("input#email").focus();
return false;
}
var message = $("input#message").val();
if (message === "") {
$("label#message_error").show();
$("input#message").focus();
return false;
}
$.ajax({
type: "POST",
url: "contact.php",
data: {name:name,email:email,message:message},
success: function() {
$('#contact_form').html("<div id='success'></div>");
$('#success').html("<h2>Your message was successfully submitted!</h2>")
.append("<p>We will get back to you within 24-48 hours.</p>")
.hide()
.fadeIn(1500, function() {
$('#success');
});
}
});
return false;
});
});
In your markup the field's id is "comments" but you are looking for "message" in your JS and PHP.
you have print your mail result
if(#mail($recipient, $subject, $formcontent, $mailheader))
{
echo "Mail Sent Successfully";
}else{
echo "Mail Not Sent";
}
Make few changes if you are using jquery 3.
Change this
$(".button").on("click", function() {
// Validation here
// Put ajax outside this block
});
Edit html form like this code.
Check the dev. tools if the action attribute is added correctly by the php.
<form id="contact" name="contact" action="<?php echo htmlspecialchars($_SERVER['PHP_SELF']); ?>" method="post" >
And ajax call into this
$("#contact").on("submit", function(e) {
e.preventDefault(); // Now the page won't redirect
var url = $(this).attr("action");
// Check console if contact is printed after the form is submitted
// If contact is printed the url is right
console.log(url);
$.ajax({
type: "POST",
url: url,
data: $(this).serialiseArray(), // Found a typo here fixed
success: function() {
// Your stuffs
}
});
});
Don't put the ajax call inside the input field verification.
Let me know if you find any issue so I can fix my code.
I am wanting to know if you can add more than one url in the action attribute in the form element? I know a lot of people are asking that but the ones I am adding in are: a php self and a mailto action. This is a feedback form so when any one sends some feedback it should check the php of validation of it and send a email at the same time once the submit button is clicked. But I tested that but when I clicked the submit button it came up as an error page. Can any one please help me?
HTML:
<form action="<?php echo htmlspecialchars($_server['php_self']);?>
, mailto:example#gmail.com" method="post" name="feedbackForm" id="ff" class="feedback"> <label for="first">First Name:</label>
<input type="text" id="first" name="fname" class="namef" placeholder="First Name" required="required"/><span class="error"><?php echo $fnameErr;?>
</span><br/>
<label for="last">Last Name:</label>
<input type="text" id="last" name="lname" class="namel" placeholder="Last Name" required="required"/><span class="error"><?php echo $lnameErr;?>
</span><br/>
<label for="mail">Email:</label>
<input type="email" id="mail" name="email" class="u-email" placeholder="any email is fine!" required="required"/><span class="error"><?php echo
$emailErr;?>
</span><br/>
<label for="yearLevel">Year Level:</label>
<select name="yearLevel" id="yearLevel" onchange="MM_jumpMenu('parent',this,0)">
<option>Year 8</option>
<option>Year 9</option>
<option>Year 10</option>
<option>Year 11</option>
<option>Year 12</option>
<option>Uni Student</option>
<option>Other</option>
</select>
<label for"comment">Comment:</label>
<textarea id="comment" name="comment" class="userComment" rows="12" cols="" "55" ">
</textarea><br/><br/>
<input type="submit" name="submitFeed" id="subff" class="sub" onclick="ask()" style="margin-left:20%;"/>
</form>
PHP:
<?php
//feedback form validation code
//start
//variables
$fnameErr = $lnameErr = $yearleErr = $emailErr = "";
$firstName = $lastName = $comment = $yearLevel = $email = "";
//the function of validation
if ($_SERVER["REQUEST_METHOD"] == "POST") {
if (empty($_POST["fname"])) {
$fnameErr = "* Your first name is required!";
} else {
$firstName = test_input($_POST["fname"]);
// check if name only contains letters and whitespace
if (!preg_match("/^[a-zA-Z]*$/", $firstName)) {
$fnameErr = "* Only letters and white space allowed!";
}
}
if (empty($_POST["lname"])) {
$lnameErr = "* Your last name is required!";
} else {
$lastName = test_input($_POST["lname"]);
if (!preg_match("/^[a-zA-Z]*$/", $lastName)) {
$lnameErr = "* Only letters and white space allowed!";
}
}
if(empty($_POST["comment"])) {
$comment = "* the comment box is required!";
} else {
$comment = test_input($_post["comment"]);
}
if (empty($_POST["email"])) {
$emailErr = "* Your email is required!";
} else {
$email = test_input($_POST["email"]);
if(!filter_var($email, FILTER_VALIDATE_EMAIL)) {
$emailErr = "* Invalid Email Format!";
}
}
}
function test_input($data) {
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
//end
?>
JS script for a confirm when the user clicks submit. so it makes sense to the form.
<script type="text/javascript">
//confrim before submitting.
function ask() {
var box = confirm("Are you sure you want to send this feeback? If yes
that you are sure click ok or if not then click canel to edit it.");
if (box == true) {
document.getElementById('firstPart').style.display = "none";
document.getElementById('nextPart').style.display = "block";
console.log("Thanks for sending your feedback");
return true;
} else {
console.log("edit!");
return false;
}
}
</script>
You couldn't add multiple actions in the form action, You should send the form to a PHP file and then after validating, send the email by PHP mail function or other libraries like PHPmailer etc.
Simple answer: No, you cannot add multiple actions for tag, how you would the distinguish between which one to choose?
If you need to select different actions according to some configuration on form choices (or whatever), use Javascript to set new action of form.
In your case, use mail PHP function to send mail from PHP script when you pass your validation.
<form action="<?php echo htmlspecialchars($_SERVER['PHP_SELF']);?>" method="post" name="feedbackForm" id="ff" class="feedback">
and then in PHP
mail('somebody#example.com', 'Subject', 'Body', optionalHeaders);
You can't do it, but you can call mailto inside your ask() like,
function ask() {
var box = confirm("Are you sure you want to send this feeback? If yes
that you are sure click ok or if not then click canel to edit it.");
if (box == true) {
document.getElementById('firstPart').style.display = "none";
document.getElementById('nextPart').style.display = "block";
console.log("Thanks for sending your feedback");
// add mailto here
myWindow=window.open("mailto:example#gmail.com");
myWindow.close();
return true;
} else {
console.log("edit!");
return false;
}
}
And change form action like,
<form action="<?php echo htmlspecialchars($_SERVER['PHP_SELF']);?>" method="post" ...>
....
</form>
I have a fully working html contact page, with a php email script, with recaptcha 2 - all of these work perfectly.
Previously, the form redirected to the php file, which showed a basic success message. Again, this worked fine.
I've tried incorporating a contact.js file onto the page, and the form submission still works, but the success message in the PHP script isn't being displayed.
I'm an idiot when it comes to JS so that's probably the issue, but any help would be gratefully received.
Here's the HTML, PHP and JS:
<form id="contact-form" method="post" action="#" role="form">
<div class="messages"></div>
<div class="controls">
<div class="row">
<div class="col-md-7">
<div class="form-group">
<label for="form_name">Name *</label>
<input id="form_name" type="text" name="name" class="form-control" placeholder="Please enter your name *" required="required" data-error="Name is required">
<div class="help-block with-errors"></div>
</div>
<div class="form-group">
<label for="form_email">Email *</label>
<input id="form_email" type="email" name="email" class="form-control" placeholder="Please enter your email address *" required="required" data-error="A valid email is required">
<div class="help-block with-errors"></div>
</div>
<div class="form-group">
<label for="form_phone">Telephone</label>
<input id="form_phone" type="tel" name="phone" class="form-control" placeholder="Please enter a contact telephone number (optional)">
<div class="help-block with-errors"></div>
</div>
<div class="form-group">
<label for="form_message">Message *</label>
<textarea id="form_message" name="message" class="form-control" placeholder="Please enter your message *" rows="4" required="required" data-error="Please enter your message"></textarea>
<div class="help-block with-errors"></div>
</div>
<p><div class="g-recaptcha" data-sitekey="xxxxxx"></div></p>
<input type="submit" class="btn btn-success btn-send" value="Submit" onClick="window.location = '#formstart'"></p>
<br><p class="text-muted"><strong>*</strong> These fields are required.</p>
</form>
PHP:
<?php
$sendTo = "email#email.com";
$subject = "New message from email.com";
$headers .= 'From: <enquiries#email.com' . "\r\n";
$name = #$_POST['name'];
$phone = #$_POST['phone'];
$email = #$_POST['email'];
$message = #$_POST['message'];
$okMessage = 'Thank you for your message. One of the team will be in touch as soon as possible.';
$errorMessage = 'There was an error while submitting the form. Please try again later';$url = 'https://www.google.com/recaptcha/api/siteverify';
$privatekey = "XXXXX";
$response = file_get_contents($url."?secret=".$privatekey."&response=".$_POST['g-recaptcha-response']."&remoteip=".$_SERVER['REMOTE_ADDR']);
$data = json_decode($response);
$emailText = "Name: $name \n Phone: $phone \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;
}
JS:
$(function () {
$('#contact-form').validator();
$('#contact-form').on('submit', function (e) {
if (!e.isDefaultPrevented()) {
var url = "contact.php";
$.ajax({
type: "POST",
url: url,
data: $(this).serialize(),
success: function (data)
{
var messageAlert = 'alert-' + data.type;
var messageText = data.message;
var alertBox = '<div class="alert ' + messageAlert + ' alert-dismissable"><button type="button" class="close" data-dismiss="alert" aria-hidden="true">×</button>' + messageText + '</div>';
if (messageAlert && messageText) {
$('#contact-form').find('.messages').html(alertBox);
$('#contact-form')[0].reset();
grecaptcha.reset();
}
}
});
return false;
}
})
});
Any help greatly appreciated!
Would:
if (messageAlert && messageText) {
$('#contact-form').find('.messages').html(alertBox);
$('#contact-form')[0].reset();
grecaptcha.reset();
}
this not clear the message you are trying to invoke?
since the class messages is the first child on "#contact-form" would it not always reset the messages you put in immediately, after putting in the data in the line before?
Also, why aren't you just toggling a modal or a popup instead of injecting an entire div dynamically? this seems like a lot of work, for something that could be done more easily with pre-loaded html? Or am I missing something obvious?
I am assuming of course that the alert, is the "success" message. But why call it an alert in your code? Why not call it successmessage? Using proper terminology will help yourself and others read your code later ;)
There is an option in the ajax method to have seperate functions for failures and successes.
I hope I helped, even if I am wrong about why you don't see your text.
try adding
if (messageAlert && messageText) {
alert("Test");
$('#contact-form').find('.messages').html(alertBox);
$('#contact-form')[0].reset();
grecaptcha.reset();
}
I'm trying to send the message, name and email from a contact form on my index page to my own email but am having some troubles. I'm using AngularJS. Right now when I click submit on the form, it just comes up with a loading screen and nothing else ever happens. This is what I currently have:
HTML:
<form ng-submit="save()" class="contactForm" name="form" ng-hide="loaded" ng-controller="formCtrl">
<input class="input" required="required" type="text" name="name" placeholder="Your Name" ng-model="message.name" />
<input class="input email" required="required" type="email" name="email" value="" placeholder="Your Email" ng-model="message.email" /><br />
<textarea class="textarea" rows="5" required="required" placeholder="Your Message" ng-model="message.text" ></textarea>
<button class="btn green">Send Message</button>
</form>
JS:
$scope.save = function () {
$scope.loaded = true;
$scope.process = true;
$http.post('sendemail.php', $scope.message).success(function () {
$scope.success = true;
$scope.process = false;
});
};
PHP (sendemail.php):
$rest_json = file_get_contents("php://input");
$_POST = json_decode($rest_json, true);
$email = $request->message.email;
$name = $request->message.name;
$message = $request->message.text;
$from="From: $name<$email>\r\nReturn-path: $email";
$subject="Message sent using your contact form";
mail("myemail#gmail.com", $subject, $message, $from);
I've also tried the following php:
var_dump($_POST);die();
$_POST = json_decode($rest_json, true);
$email = $_POST["message.email"]; //$request->message.email;
$name = $_POST["message.name"]; //$request->message.name;
$message = $_POST["message.text"]; //$request->message.text;
$from="From: $name<$email>\r\nReturn-path: $email";
$subject="Message sent using your contact form";
mail("myemail#gmail.com", $subject, $message, $from);
Should the php be in the same folder as the javascript? Any help would be much appreciated! Thanks very much.
You making POST ajax request, so in order to use data that you're trying to transfer to your PHP application, you need to find it in $_POST array. More about it here
More specifically you don't need this line $rest_json = file_get_contents("php://input");
You just need to get data from $_POST. Just make var_dump($_POST);die(); to debug what's in there and what you need to decode exactly.