I have been fighting with this for quite awhile, searching questions, tutorials, and forums to not find a working solution. I'm extremely green in the realm of PHP and just now starting to learn.
Page in progress can be found here: http://williamsfuller.com/limedropdesign/
Goal: Use front end validation using jQuery Validate (http://jqueryvalidation.org/), if validation is successful then in the submitHandler run an ajax call to a php file that takes the form values and posts them to the server. On the ajax.done function clear the form and show that the submission has been successful.
Reason I'm using ajax is because I don't want the page to refresh and send the user back to the top of the page. This is a single page portfolio and if I was to do a post method on the form it will ruin the experience by reloading the page.
What I have achieved thus far:
-I have the jQuery validation working
-If the validation is successful the ajax call runs correctly activating the contact form submission file
-On the ajax.done function the contact form clears and a success message slides down telling the user the message has been sent
-On the php side of things I was able to hardcode a mail function that runs which tells me that the ajax call is working and the php file is working.
<?php
mail('email#gmail.com', 'Mail from Lime Drop Design', 'some body content for the email ');
?>
Where I'm stuck is taking the jQuery values and putting them into a working if($_POST){} and having that send off an email.
I also have a honey pot in the form to catch some bots, if all the information is validated and the subject field is still filled out I'm looking to just allow the POST to die.
HTML:
<form id="contactForm" method="get" action="">
<div class="form-group">
<input class="form-control"
type="text"
name="name"
id="name"
minlength="2"
placeholder="Name" required>
</div>
<div class="form-group">
<input class="form-control"
type="email"
name="email"
id="email"
placeholder="Your email address" required>
</div>
<div class="form-group">
<textarea class="form-control contactMessage"
name="message"
id="message"
rows="8"
minlength="10"
placeholder="Enter a message" required></textarea>
</div>
<input type="text" id="subject" name="subject" autocomplete="off">
<div class="form-actions">
<input type="hidden" name="save" value="contact">
<button id="formSubmit" type="submit" class="btn contact-btn pull-right">Send</button>
</div>
<div id="result">
Thank you, your message has been sent to Liz!
</div>
</form>
JavaScript:
$(document).ready(function(){
$('#result').hide();
$.validator.setDefaults({
submitHandler: function() {
var nameValue = $('#name').val();
var emailValue = $('#email').val();
var messageValue = $('#message').val();
console.log(nameValue, emailValue, messageValue);
$.ajax({
type: "GET",
url: "contactSubmission.php",
data: {
name: $('#name').val(),
email: $('#email').val(),
message: $('#messageValue').val()
}
}).done(function(){
$('#contactForm').find("input[type=text], input[type=email], textarea").val("");
$('#result').slideDown();
});
}
});
$("#contactForm").validate();
)};
PHP Working:
<?php
mail('email#gmail.com', 'Mail from Lime Drop Design', 'some body content for the email outisde post function');
?>
PHP not working (what I'm trying to achieve):
<?php
if($_POST){
$to = 'email#gmail.com';
$subject = 'Contact Form Submission';
$message = $_POST['messageValue'];
if($_POST['subject'] != ''){
die();
}
//Sanitize input data using PHP filter_var().
$nameValue = filter_var($_POST["nameValue"], FILTER_SANITIZE_STRING);
$emailValue = filter_var($_POST["emailValue"], FILTER_SANITIZE_EMAIL);
$messageValue = filter_var($_POST["messageValue"], FILTER_SANITIZE_STRING);
mail($to, $subject, $message);
}
?>
Any help on this would be greatly appreciated. I have been trying to get this to work for awhile now and I seem to just be stuck on the php POST at this point. Thanks in advance for any input or working example.
As pointed out, you're making a GET request with Jquery while php expect a POST one.
Then on your php, the post fields aren't good: You put 'Value' post field:
$_POST["nameValue"] while on Jquery it seems like the field is named name, try changing $_POST["nameValue"] to $_POST["name"] And do the same for message and email.
EDIT : Change $('#messageValue').val() to $('#message').val() in the post datas in your Jquery code, this value was the reason why the data wasn't succefully sent to PHP, in you console.log you've put the right ID but not in the post data, that's why you where thinking the correct values was sent by php.
Related
I am using a form for people to submit contact requests for a website. I'm using JS and HTML for this website. I've tried to use mailto but it doesn't actually send anything to my email when I press submit. I don't want to use PHP if I can avoid it since I don't know PHP that well.
Here is my HTML
<form method=POST action="mailto:naomikudren#gmail.com" enctype="text/plain">
Company<br>
<input type="text" name="companyname"><br>
Contact Person<br>
<input type="text" name="contactname"><br>
Phone number<br>
<input type="tel" name="phonenumber" min="6" max="15"><br>
Email<br>
<input type="email" name="email"><br>
Message<br>
<input type="textarea" name="message" style='white-space:pre-wrap; height:200px;width:500px;'><br>
<input type="submit" value="Submit">
</form>
I haven't done anything in the JS document for this to work. Do I have to use some sort of command for when submit is pressed in JS or should it be enough to do all this in HTML?
You cant send email directly using Javascript, leave aside HTML.
what you can do is open another window with Mail To option.
window.open('mailto:test#example.com');
//or with subject using below
window.open('mailto:test#example.com?subject=subject&body=body');
Otherwise you can do AJAX call to server which sends mail, but that will need PHP or other backend programming.
You have to use a server side language to send emails .. You cannot do it using client side language like js. So better use a simple php function to send email. It's not difficult ...
You cant send email directly using Javascript. For this you have to use php Mailing function, which has a very simple syntax.
<?php
// the message
$msg = "First line of text\nSecond line of text";
// use wordwrap() if lines are longer than 70 characters
$msg = wordwrap($msg,70);
// send email
mail("someone#example.com","My subject",$msg);
?>
"NO! JavaScript can't email a form! but, there are alternatives to send the form data to an email address.
There is no direct method provided by JavaScript to send the data submitted in the form to an email address.
The main concern for not providing a ‘JavaScript email form’ feature is security."
Hello,
i'm trying to create a Windows 10 App with Javascript for self education. Today i want to try, send a email with message, Name from a Contact form. I'm only beginner on Javascript. can someone write a short code with example? I have a Contact form with PHP, but how can i send a Mail with Javascript?
<form method="post" action="send.js">
<input type="text" placeholder="Name" name="name" id="name" required=" ">
<input type="email" placeholder="Email" name="email" id="email" required=" ">
<textarea placeholder="Message..." name="msg" id="msg" required=" "></textarea>
<input type="submit" value="Submit">
</form>
Thanks
If you want to send e-mails via JavaScript, use Node.js Nodemailer.
https://nodemailer.com/Nodemailer - Send e-mails with Node.JS
You could also use
Send email
And that will open the default mail application on the user's device, and automatically fill in the To: field with that e-mail address.
Here is an example of how it works.
It is also possible to specify initial values for headers (e.g. subject, cc, etc.) and message body in the URL. Blanks, carriage returns, and linefeeds cannot be embedded but must be percent-encoded.
Send email
As far as I know you can't send mail with javascript. Normally you'd use javascript to send your form to your php page. You could use something like jquery and ajax the form to you php script so:
$(document).ready(function(){
$('#your-form-id').on('submit', function(){
var formData = $(this).serialize
$.ajax({
type: 'post',
url: 'your_url.php',
data: formData,
dataType: 'json',
success: function(response){
//Anything you want to do after form is submitted
}
});
});
});
This isn't tested code but I think it should be roughly right.
So i'm working on form validation for a website.
What i have accomplished so far is when the form is submitted, validate.php checks if the email is in the correct format.
If it is, it proceeds in calling the sendMail() function included in the validate.php which proceeds in sending the email and then redirects the user back to the home page after 5 seconds. (This part works <-)
If it isn't, that's where i'm stuck.
What i'm trying to accomplish at this stage, is somehow get PHP to send a script tag, <script> emailError(); </script>, to the current page (contact.html) and execute the script which simply appends a paragraph saying that the email is incorrect. What i am getting, however is the validate.php has its own error in the else statement simply saying Error in a blank page (which is what i don't want, i put it there to see if the validation was working correctly).
I tried to add this (the script mentioned above) in the else statement in validate.php:
validate.php
<?php
include "mail.php";
$email = $_POST['email'];
if (!filter_var($email, FILTER_VALIDATE_EMAIL) === false) {
sendMail();
}else {
echo("<script> emailError(); </script>");
}
?>
So what i was hoping it would do, is echo it into the page executing the JavaScript function but it didn't work and i think i know why.
PHP, to my knowledge, executes on request of user interaction (press button, click something, etc...) or upon page loading (Correct me if i'm wrong, still learning).
To make sure that the echo did not work, i inspected the page in real-time while using the form and didn't see any sign of the script tag being inserted into the HTML.
At this point, i have tried many alternative solutions, i don't even know where to begin. I could really use some help and any tips for improving my form.
This is the contact page that i'm working on. Feel free to try it out and see the results for yourself but Please don't spam!
Click Here
emailError.js
This is what i wanted to echo into the page with PHP.
function emailError(){
var targetElement = document.getElementById("emailform");
var errorElement = document.createElement("P");
var errorMessage = document.createTextNode("Invalid Email");
errorElement.appendChild(errorMessage);
errorElement.setAttribute("id","error");
document.body.appendChild(errorElement);
}
contact.html
This is just a segment of contact.html showing my form.
<form action="validate.php" method="post" id="emailform">
<required>* - Required</required><br>
<name>Name:* <input type="text" name="name" id="name" required /></name><br>
<email>Email:* <input type="text" name="email" id="email" required /></email> <br>
<message>Message:*<br><textarea rows="5" name="message" id="message" maxlength="1000" required></textarea></message><br>
<submit><input type="submit" value="Send" name="send" id="send" /></submit>
</form>
I'm not asking for something to copy n' paste, simply something to push me in the right direction.
Well, first of all, You are submitting your form to validate.php, and then never redirect back to contact.html, that's why you dont see the script tag appended. And from whay i see, that string 'Error' does not appear to be in your code, so I'm guessing that you did not paste the entire code. My suggestion, is to redirect to the contact form back again if the condition fails, and change contact.html to contact.php in order to be able to do a validation. Here is some rough code:
<?php
include "mail.php";
$email = $_POST['email'];
if (!filter_var($email, FILTER_VALIDATE_EMAIL) === false) {
sendMail();
}else {
header('Location: contact.php?error=1');
}
?>
and then, in your contact.php file:
<form action="validate.php" method="post" id="emailform">
<required>* - Required</required><br>
<name>Name:* <input type="text" name="name" id="name" required /></name><br>
<email>Email:* <input type="text" name="email" id="email" required /></email> <br>
<message>Message:*<br><textarea rows="5" name="message" id="message" maxlength="1000" required></textarea></message><br>
<submit><input type="submit" value="Send" name="send" id="send" /></submit>
</form>
if ($_GET['error']) {
echo "<script> emailError(); </script>";
}
This is just a rough example, it can be more robust, with this solution, if somebody enters your contact form with the query param "error" he will get the javascript executed. But as I said, this is a concept and a rough solution to explain how you could solve your problem.
You can't execute java function like you are trying to.
If you use ajax, than in the success response function, set the respone to a div.
For example, if you have a success function that gets the data in an argument called data, than set an empty div with an ID like "emailResponse" in your page, and use this in the function:
var responseDiv = document.getElementById("emailResponse");
responseDiv.innerHtml = data;
Add this to your html:
<form action="validate.php" method="post" id="emailform">
<required>* - Required</required><br>
<name>Name:* <input type="text" name="name" id="name" required /></name><br>
<email>Email:* <input type="text" name="email" id="email" required /></email> <br>
<message>Message:*<br><textarea rows="5" name="message" id="message" maxlength="1000" required></textarea></message><br>
<submit><input type="submit" value="Send" name="send" id="send" /></submit>
<div id="emailResponse"></div>
</form>
And in your PHP, change to this:
if (!filter_var($email, FILTER_VALIDATE_EMAIL) === false) {
sendMail();
echo "Your message was sent!";
}else {
echo "You email was invalid!";
}
UPDATE:
If you are not using ajax - you need to redirect to the contact page with some parameter in GET, or set some SESSION variable.
I a have PHP form where I collect a bunch of values from text inputs, but for one input I have the input filled in via javascript (user selects a date from a calendar, that date then populates a text input). I've setup a simplified version of this:
<?php
$displayForm = true;
if ($_POST['submitFlag'] == 1) {
// Form was submitted. Check for errors and submit.
$displayForm = false;
$installationTime = $_POST['installation-time'];
// send e-mail notification
$recipients = "test#test.com";
$subject = "Test Email - Test Form Submission";
$message = wordwrap('Someone has filled out the secure form on test.com. Here\'s what they had to say:
Installation Time: ' . $installationTime .'
');
$headers = "From: test#test.com";
mail($recipients, $subject, $message, $headers);
// Output thank you message
?>
<h2>Thank You!</h2>
<?php if($installationTime == NULL){echo 'test failed: value submitted was null.';}else{echo 'test passed: value submitted was not null.';} ?>
<p>Your form has been submitted. Thank you for your interest in test.com.</p>
<?php
}
if ($displayForm) {
// If form was not submitted or errors detected, display form.
?>
<div class="note"><span class="required">*</span> Click me to set value of input.</div>
<form name="contactForm" id="contactForm" method="post" enctype="multipart/form-data" action="<?php echo $_SERVER['PHP_SELF']; ?>?state=submit">
<label for="installation-time" class="service-time">The time you have selected for installation is: <span class="required">*</span></label>
<input type="text" name="installation-time" id="installation-time" disabled value="<?php echo $_POST['installation-time']; ?>" />
<input type="hidden" name="submitFlag" id="submitFlag" value="1" />
<input type="submit" name="submit" id="submit" value="Sign-Up" />
</form>
<?php
} // End of block displaying form if needed.
?>
And then in jQuery I do one of these:
$('.note').click(function(){
$('#installation-time').val('test string');
});
When I submit the form, the PHP variable that's supposed to collect that value is null. Every other input in the form works, and if I remove the javascript and manually enter the exact same text that I had set with JavaScript into the input it works as well.
The question really is why populating a field with javascript as opposed to manually typing the exact same string into a text input would break things. Again there are no errors and the input is populated correctly on the front end. Somehow posting the form just doesn't pick up on the value when it's set by javascript vs. typed manually. There has to be something really fundamental I'm missing here.
Any idea what's going on here? I've spent hours puzzling over this to no avail.
Update:
Code updated, test page:
http://dev.rocdesign.info/test/
Solution: can't post a disabled input. I actually tested that back in the beginning and must have missed that removing the "disabled" on the input made it work, so I mistakenly ruled it out and moved on.
Thanks for the responses everyone. And for anyone else with this problem: use a hidden input to post the value.
I made a small form and I want it to post information back to the user when the inputs are left blank.
For some reason it says please use post request, so I added it and now it gives me a different error message.
Here is the code:
http://jsfiddle.net/pwtnY/
<div id="main">
<form name="myForm" method="post">
<label><span>First Name:</span><input type="text" class="firstname" name="fname"></label><br/>
<label><span>Last Name:</span><input type="text" class="lastname"></label><br>
<label><span>E-Mail:</span><input type="text" class="email"></label><br/>
<label><span>Phone:</span><input type="text" class="phone"></label><br/>
<input type="submit" name="submit">
</form>
<div id="answer"></div>
</div>
Javascript:
$(document).ready(function(){
$('input:submit').click(function(){
$firstname = $('.firstname').val();
$lastname = $('.lastname').val();
$email = $('.email').val();
$phone = $('.phone').val();
if($firstname === "" && $lastname==="" && $email ==="" && $phone === ""){
$("#answer").html("Please fill out all fields.");
}
});
});
Anyone know what the problem could be and how I could go about solving it?
When you click submit, the form is actually posting to your django backend. If you want to do frontend validation before posting to your server, prevent the submit button from actually posting.
$('input:submit').click(function(event){
event.preventDefault();
$firstname = $('.firstname').val();
In your fiddle you haven't included jquery library. If you don't want to submit anything to the server, replace submit button with simple button <input type="button" value="submit">. There is updated your example: fiddle
P.S. You probably want to use OR instead of AND in your validation to validate if any of the fields is empty