"Undefined" response when submitting contact form without page refresh - javascript

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.

Related

Submit a HTML form without redirection and showing a success message

I decided to switch from a WordPress website to a self-made with HTML, CSS and JS, aiming to improve performance. So far, relying on tutorials, I've managed to deal with almost every issue, but I just can't get the contact form work the way it worked in WP. So far it redirects me to another page that shows the success message, which is just ugly.
Basically, I want the submit button to do 3 things: 1. Not to redirect me to another page. 2. Reset the form. 3. Display a success message.
Read many similar questions here, but as I am completely unfamiliar with AJAX, finally decided to post this question. Here's my code:
Index.html:
<div>
<form method="post" action="form.php" name="myForm">
<input name="name" placeholder="Nombre" required>
<input name="email" type="email" placeholder="Correo Electrónico" required>
<textarea rows="10" name="message" placeholder="Mensaje" required></textarea>
<input id="submit" name="submit" type="submit" value="Enviar Mensaje" class="boton-rojo">
</form>
</div>
and in form.php:
<?php
$name = $_POST['name'];
$email = $_POST['email'];
$message = $_POST['message'];
$formcontent="De: $name \n Mensaje: $message";
$recipient = "contacto#mydomainname.cl";
$subject = "Mensaje desde el sitio web";
$mailheader = "From: $email \r\n";
mail($recipient, $subject, $formcontent, $mailheader) or die("Error!");
echo "Tu consulta fue recibida";
?>
Any help would be much appreciated.
Thanks.
Put an ID to your form
<form id='myForm'>
....
</form>
Use jQuery (For easy code)
....
<script
src="https://code.jquery.com/jquery-3.4.1.min.js"
integrity="sha256-CSXorXvZcTkaix6Yvo6HppcZGetbYMGWSFlBw8HfCJo="
crossorigin="anonymous"></script>
</body>
Use $.ajax
$('#myForm').submit(function(e) {
e.preventDefault(); // prevent from submitting form directly
$.ajax({
url: 'form.php',
method: 'post',
data: $("#myForm").serializeArray() // convert all form data to array (key:value)
})
.done(function(response){
alert(response); // show the response
$("#myForm").reset(); // reset the form
})
.fail(function(error){
alert(error); // show the error.
});
})

Why cant ajax find php file when submitting form?

I have a form, making an ajax post request but it wont find the php file.Ive tried anything and read through so many posts here and tried everything suggested but nothing helps.
I tried to use an absolute path as that was suggested somewhere. Doesnt work.
relative path doesnt work either
I tried to put the submit button outside of my form in my html file (was suggested in another post) - doesnt work either.
Anyone knows why?
EDIT: Im getting a 404
file structure:
myApp/app/js/contact.js
myApp/app/mail/contact.php
myApp/app/index.html
html:
<section id="contact">
<form>
name:
<input id="name" type="text" name="name"> email:
<input id="email" type="text" name="email"> message:
<input id="message" type="text" name="message">
<button id="submit">send</button>
</form>
</section>
app/js/contact.js:
$('#submit').click(function (event) {
event.preventDefault() ;
var name = $("#name").val();
var email = $("input#email").val();
var message = $("textarea#message").val();
console.log("name", name, email);
$.ajax({
url: "/app/mail/contact.php",
type: "POST",
data: {
name: name,
email: email,
message: message
}
})
});
mail/contact.php:
<?php
if (isset($_POST["submit"])) {
$name = $_POST['name'];
$email = $_POST['email'];
$message = $_POST['message'];
$from = 'Contact Form';
$to = 'myemail#yahoo.com';
$subject = 'Message from my page ';
if (mail ($to, $subject, $body, $from)) {
$result='<div class="alert alert-success">Thank You! I will be in touch</div>';
}
}
?>
This isn't going to solve your issue, but this is a better ux
give your <form> a class or ID and execute your form submission on a form submit
so it would be
$('.formClassName').submit(function(event){
});
This will allow the form submission to fire off the AJAX event on the submit button click, as well as if the user hits the enter button.
In your html file, put your scripts before </body> tag
<section id="contact">
<form>
name:
<input id="name" type="text" name="name"> email:
<input id="email" type="text" name="email"> message:
<input id="message" type="text" name="message">
<button id="submit">send</button>
</form>
</section>
<script type="text/javascript" src="//code.jquery.com/jquery-3.2.1.min.js"></script>
<script type="text/javascript" src="/app/js/contact.js"></script>
</body>
Instead of using
url: "/app/mail/contact.php",
use:
url: "mail/contact.php",

HTML: Get value from text fields and email them

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;

Php mail being sent from simple POST request but not when using AJAX

So I have a website with a simple contact form and I would like to receive the message by email.
I created my mail.php handler :
<?php
$owner_email = "somebody#somemail.com";
$headers = 'From:' . $_POST["email"];
$subject = 'A message from your site visitor ' . $_POST["name"];
$messageBody = "";
// some verifications
try{
if(!mail($owner_email, $subject, $messageBody, $headers)){
throw new Exception('mail failed');
}
else{
echo 'mail sent';
}
}
catch(Exception $e){
echo $e->getMessage() ."\n";
}
?>
If I create a simple HTML form like this :
<form method="post" action="mail.php">
<label>Name</label>
<input name="name" placeholder="Type Here">
<label>Email</label>
<input name="email" type="email" placeholder="Type Here">
<label>Message</label>
<textarea name="message" placeholder="Type Here"></textarea>
<input id="submit" name="submit" type="submit" value="Submit">
</form>
everything works fine and I receive the email in my mailbox.
If I send a POST request from my browser at http://mywebsite.com/mail.php the answer is "mail sent" and I receive the email in my mailbox.
However when I want to use some JavaScript to dynamically validate the form fields and then send the POST request by using Ajax I don't receive anything. Here is my JavaScript :
mailHandlerURL:'mail.php',
...
// on submit when all validations are OK
$.ajax({
type: "POST",
url:_.mailHandlerURL,
data:{
name:_.getValFromLabel($('.name',_.form)),
email:_.getValFromLabel($('.email',_.form)),
phone:_.getValFromLabel($('.phone',_.form)),
message:_.getValFromLabel($('.message',_.form)),
stripHTML:_.stripHTML
},
success: function(response){
console.log(response);
_.showFu(); // to display to the user that the email has been sent
}
})
console.log() shows : "mail sent" so the mail.php is called correctly.
The application is hosted on OpenShift and uses PHP 5.4

Can I call a php file on form submit, and call or echo a JS function from that?

So I'm basically trying to create an HTML form that will
process my login through php POST method
close my login lighbox with javascript, or display an error (right now I'm using JS to change an invisible form value under the login form.
HTML
if (isset($_GET['error'])) {
echo '<p class="error">Error Logging In!</p>';
}?>
<br />
<form action="process_login.php" method="post" name="login_form">
Email: <input class="searchform" type="text" name="email" size="20"/><br />
Password: <input class="searchform" type="password"
name="password"
id="password" size="20"/><br />
<input type="button" class="searchform"
value="Submit" size="40" style="height:45px; width:90px"
onclick="formhash(this.form, this.form.password);" />
<input type="text" id="errorbox" style="height:45px; width:180px" value=""><br>
</form>
here's the php file:
if (isset($_POST['email'], $_POST['p'])) {
$email = $_POST['email'];
$password = $_POST['p'];
if (login($email, $password, $mysqli) == true) {
// Login success
echo "<script>document.getElementById('light').style.display=
'none';document.getElementById('fade').style.display= 'none'</script>";
} else {
// Login failed
echo "<script>document.getElementById('errorbox').value='Error'</script>";
}
} else {
// The correct POST variables were not sent to this page.
echo 'Invalid Request';
}
I know I'm not doing this right, I'm just not sure HOW to do it at all...
Well, yes, technically you can do that, but it is a VERY bad practice, and extremely not clean.
what you'd prefer to do is use Ajax, and do those JS actions in it's success callback:
Note: you will need to include the jQuery lib in your scripts.
Another none: if you don't have PHP 5.4 on your server, just remove the second callback function, and handle all the scenarios in the success callback
!(function($){
$(function() {
$('#submitBtn').on('submit', function(){
$.post('process_login.php', $('form[name="login_form"]').serialize(), function(data){
//data is a json object which contans the reponse
data = $.parseJSON(data);
$("fade").fadeOut();
$("light").fadeOut();
},
function(data){//error callback
data = $.parseJSON(data);
if(data.forbidden){
$("#errorBox").html("Error!");
}
else if(data.error){
$("#errorBox").html("Invalid request!");
}
});
});
});
})(window.jQuery);
HTML:
<form name="login_form">
<div>
<input type="text" name="email" placeholder="email">
</div>
<div>
<input type="password" name="p" placeholder="password">
</div>
<div>
<input type="button" id="submitBtn" value="Login">
</div>
</from>
PHP:
$response = array();
if (isset($_POST['email'], $_POST['p'])) {
$email = $_POST['email'];
$password = $_POST['p'];
if (login($email, $password, $mysqli) == true) {
http_response_code(200);//HTTP OK, requires php 5.4
$response['success'] = true;
} else {
// Login failed
$response['forbidden'] = true;
http_response_code(401);//HTTP forbidden
}
} else {
// The correct POST variables were not sent to this page.
$response['error'] = true;
http_response_code(400);//HTTP bad request
}
echo json_encode($response);
add onsubmit event attribute to the form:
<form onsubmit="return validate();">...
where validate() is a js function that closes lightbox and returns true if form is ok, or displays errors and returns false if form is bad.

Categories