event.preventDefault(); not working when submitting form - javascript

I am trying to put the result from a submitted form in to a div instead of opening it inside a new window. The problem is that my event.preventDefault(); doesn't seem to be working and I don't understand why. The result, after I hit the submit button is always to open the contact-form-handler.php, which is the script file.
Here is the code:
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
CONTACT FORM:
<form class="form-container" id="contactForm" method="post" action="contact-form-handler.php">
<div class="form-title">Full Name:</div>
<input class="form-field" type="text" name="name" /><br />
<div class="form-title">Email Address:</div>
<input class="form-field" type="text" name="email" /><br />
<div class="form-title">Phone Number:</div>
<input class="form-field" type="text" name="phone" /><br />
<div class="form-title">Message:</div>
<textarea class="form-field" rows="8" cols="34" name="message"></textarea><br />
<div id="contactResponse"></div>
<div class="submit-container">
<button type="submit" class="submit-button">Send</button>
</div>
</form>
SCRIPT CODE:
<script type="text/javascript">
$("#contactForm").submit(function(event)
{
/* stop form from submitting normally */
event.preventDefault();
/* get some values from elements on the page: */
var $form = $( this ),
$submit = $form.find( 'button[type="submit"]' ),
name_value = $form.find( 'input[name="name"]' ).val(),
email_value = $form.find( 'input[name="email"]' ).val(),
phone_value = $form.find( 'input[name="phone"]' ).val(),
message_value = $form.find( 'textarea[name="message"]' ).val();
/* Send the data using post */
var posting = $.post( "contact-form-handler.php", {
name: name_value,
email: email_value,
phone: phone_value,
message: message_value
});
posting.done(function( data )
{
/* Put the results in a div */
$( "#contactResponse" ).html(data);
/* Change the button text. */
$submit.text('Sent, Thank you');
/* Disable the button. */
$submit.attr("disabled", true);
});
});
</script>
PHP CODE:
<?php
$myemail = 'mymail#mail.com';//<-----Put Your email address here.
$name = $_POST['name'];
$phone = $_POST['phone'];
$email_address = $_POST['email'];
$message = $_POST['message'];
$to = $myemail;
$email_subject = "Contact form submission: $name";
$email_body = "Contact Form Emocool Website ".
" Here are the details:\n Name: $name \n Telefono: $phone \n Email: $email_address \n Message \n $message";
$headers = "From: $myemail\n";
$headers .= "Reply-To: $email_address";
if(mail($to,$email_subject,$email_body,$headers))
{
echo "Thank you for contacting us";
}
//redirect to the 'thank you' page
else
{
echo "Sorry, there has been an error";
}
?>
So the problem is when I hit the submit button, instead of the result showing inside the #contactResponse div, it is showing inside new page of the script contact-form-handler.php
Any suggestions why this is not working?

My best guess is that you are adding your #contactForm submit listener before the form is actually rendered. Try wrapping your jQuery in $(document).ready(function () {});
I don't see any other issues.

Using <script type="text/javascript"> , your script will not work, replace <script type="text/javascript"> with <script language="javascript">, It will work correctly. But language="javascript" is deprecated in favor of type="text/javascript". keep in mind you put the code $(document).ready(function(){ //code to be implemented// });
Anyhow your script will work by replacing type="text/javascript" with language="javascript"

Related

"Undefined" response when submitting contact form without page refresh

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.

500 error on localhost when submitting form using AJAX and PHP

I'm fairly new to PHP and I'm having trouble sending test emails out from my local host.
I have a 3 field form where I'm hoping that I can have a user submit the form & be able to see a success message without the page refreshing. I get the error message that I have set in the code but for some reason, I'm unable to actually get the emails to send/have a success message appear.
Here's my code:
js
jQuery( document ).ready( function( $ ) {
var form = $('#ajax-contact');
var formMessages = $('#form-messages');
$(form).submit(function(e) {
e.preventDefault();
var formData = $(form).serialize();
$.ajax({
type: 'POST',
url: $(form).attr('action'),
data: formData
})
.done(function(response) {
$(formMessages).removeClass('error');
$(formMessages).addClass('success');
$(formMessages).text(response);
$('#name, #email, #number').val('');
})
.fail(function(data) {
$(formMessages).removeClass('success');
$(formMessages).addClass('error');
if (data.responseText !== '') {
$(formMessages).text(data.responseText);
} else {
$(formMessages).text('Oops! An error occured and your message could not be sent.');
}
});
});
});
mailer.php
<?php
if ($_SERVER["REQUEST_METHOD"] == "POST") {
$name = strip_tags(trim($_POST["name"]));
$name = str_replace(array("\r","\n"),array(" "," "),$name);
$email = filter_var(trim($_POST["email"]), FILTER_SANITIZE_EMAIL);
$number = trim($_POST["number"]);
if ( empty($name) OR empty($number) OR !filter_var($email, FILTER_VALIDATE_EMAIL)) {
http_response_code(400);
echo "Sorry, there seems to be a problem submitting your details, please try again or contacts us";
exit;
}
$recipient = "example#example.co.uk";
$subject = "$name has given you their details to call them back";
$email_content = "
<html>
<style>
body {
background-color: white;
}
.email-container{
background-color:#c1c1c1;
max-width:400px;
margin:0 auto;
padding:30px 10px;
border-radius:10px;
border: 2px solid #515151;
}
</style>
<body>
<div class="email-container">
Dear example, <br />
<br />
A potential client has requested a call back. Their details are as follows: <br />
<br />
Name: $name\n <br />
Email: $email\n\n <br />
Telephone: \n$numer\n
</div>
</body>
</html>"
$email_headers = "From: $name <$email>";
if (mail($recipient, $subject, $email_content, $email_headers)) {
http_response_code(200);
echo "Thank You! Your message has been sent.";
} else {
http_response_code(500);
echo "Sorry, there seems to be a problem submitting your details, please try again or contacts us";
}
} else {
http_response_code(403);
echo "There was a problem with your submission, please try again.";
}
?>
HTML
<form class="requestcall-form" id="ajax-contact" method="post" action="mailer.php">
<input type="text" id="name" name="name" placeholder="Full Name" required>
<input type="text" id="email" name="email" placeholder="Email Address" required>
<input type="text" id="number" name="number" placeholder="Contact number" required>
<input class="submit" type="submit" name="submit" value="Submit">
</form>
<div id="form-messages"></div>
there is something wrong with how you output $email_content. String is not formatted correctly
check the <div class="email-container"> and change it to <div class='email-container'>
also, add a (;) after your $email_content
The other answer is correct, I thought I'd offer a better solution for dealing with large blocks of text, heredoc strings. No worrying about unescaped quotes ruining your day. Using this, your code would look like this:
...
$recipient = "example#example.co.uk";
$subject = "$name has given you their details to call them back";
$email_content = <<< HTML
<html>
<style>
body {
background-color: white;
}
.email-container{
background-color:#c1c1c1;
max-width:400px;
margin:0 auto;
padding:30px 10px;
border-radius:10px;
border: 2px solid #515151;
}
</style>
<body>
<div class="email-container">
Dear example, <br />
<br />
A potential client has requested a call back. Their details are as follows: <br />
<br />
Name: $name <br />
Email: $email <br />
Telephone: $numer
</div>
</body>
</html>
HTML;
$email_headers = "From: $name <$email>";
...

$_POST[] not catching HTML form input

I have a strange problem, I am passing data from an email form (HTML5) to ajax/JSON and returning false so the page does not redirect to the php script after the submit button is pressed.
If I put commas seperating each data param ($email, $name, $message), only 'name' and 'email' get passed to $_POST[], leaving out the value of$message.
However if there are no commas between the params all the inputs are caught by $_POST[].
For example (with commas): (does not redirect to php script but $message value is not caught in $_POST[])
var form = $('.contact-form');
form.submit(function (evt) {
$this = $(this);
$.post('Scripts/php/sendemail.php',{
name: $('input[name=name]').val(),
email: $('input[name=email]').val(),
message: $('input[name=message]').val()
}, function(data) {
$this.prev().text(data.message).fadeIn().delay(3000).fadeOut();
},'json');
evt.preventDefault();
return false;
});
Output:
$name=foo
$email=bar
$message=null
Page returns false
(without commas): (redirects to php script but $message value is caught in $_POST[])
var form = $('.contact-form');
form.submit(function (evt) {
$this = $(this);
$.post('Scripts/php/sendemail.php',{
name: $('input[name=name]').val()
email: $('input[name=email]').val()
message: $('input[name=message]').val()
}, function(data) {
$this.prev().text(data.message).fadeIn().delay(3000).fadeOut();
},'json');
evt.preventDefault();
return false; (does not redirect to `php`)
});
Output:
$name=foo
$email=bar
$message=bar
HTML Form:
<form id="main-contact-form" class="contact-form" name="contact-form" method="post" action="Scripts/php/sendemail.php">
<div class="row">
<div class="col-sm-6">
<div class="form-group">
<input type="text" name="name" class="form-control" required="required" placeholder="Name">
</div>
</div>
<div class="col-sm-6">
<div class="form-group">
<input type="email" name="email" class="form-control" required="required" placeholder="Email address">
</div>
</div>
</div>
<div class="row">
<div class="col-sm-12">
<div class="form-group">
<textarea name="message" id="message" required="required" class="form-control" rows="8" placeholder="Message"></textarea>
</div>
<div class="form-group">
<button type="submit" id="submit" class="btn btn-danger btn-lg">
Send Message
</button>
</div>
</div>
</div>
</form>
JS for form:
var form = $('.contact-form');
form.submit(function (evt) {
$this = $(this);
$.post('Scripts/php/sendemail.php',
{name: $('input[name=name]').val(),
email: $('input[name=email]').val(),
message: $('input[name=message]').val()
}, function(data) {
$this.prev().text(data.message).fadeIn().delay(3000).fadeOut();
},'json');
evt.preventDefault();
return false;
});
PHP handler:
<?php
header('Content-type: application/json');
$status = array(
'type'=>'success',
'message'=>'Email sent! Thankyou :)'
);
$name = $_POST['name'];
$email = $_POST['email'];
$subject = 'query';
$message = $_POST['message'];
$email_from = $email;
$email_to = 'keilcarpenter01#gmail.com';
$body = 'Name: ' . $name . "\n\n" . 'Email: ' . $email . "\n\n" . 'Subject: ' . $subject . "\n\n" . 'Message: ' . $message;
$success = mail($email_to, $subject, $body, 'From: visitor');
echo json_encode($status);
#start buffering (all activity to the buffer)
ob_start() ;
# dumps to buffer
var_dump($_POST) ;
# dump buffered $classvar to $outStringVar
$outStringVar = ob_get_contents() ;
# open your file with append, read, write perms
# (be sure to check your file perms)
$fp=fopen('dmp.txt','a+');
# write output to file & close it
fwrite($fp, $outStringVar );
fclose($fp);
# clean the buffer & stop buffering output
ob_end_clean() ;
die;
In this case how does the comma seperatores determine what input by form gets caught by $_POST[]?
You have to change the jquery for get value of textarea, try following code for that :-
var form = $('.contact-form');
form.submit(function (evt) {
$this = $(this);
$.post('Scripts/php/sendemail.php',
{name: $('input[name=name]').val(),
email: $('input[name=email]').val(),
message: $('textarea[name=message]').val()
}, function(data) {
$this.prev().text(data.message).fadeIn().delay(3000).fadeOut();
},'json');
evt.preventDefault();
return false;
});
It may help you.
Use:
message: $('textarea[name=message]').val()

Need help adding Email Validation and hiding form after submit

I am new to PHP and am having trouble with adding email validation and then hiding the form after pressing the submit button. I have an error.php, thankyou.php and formmail.php. The PHP code below is that of formmail.php. I just don't know what to write for email validation for this specific code. I've tried copying some PHP codes from other sites but it just doesn't match up with my code. And as far as hiding the form after submit, I really don't know what to do with that.
Here is my HTML:
<div id="contact">
<div id="contact-left">
<form id="ajaxsubmit" action="formmail.php" method="post">
<div class="form">
<div class="formblock">
<h2>Name</h2>
<input name="name" type="text" class="required txt" id="name" />
</div>
<div class="formblock">
<h2>Email</h2>
<input name="email" class="required txt" type="text" id="email" />
</div>
<div class="formblock">
<h2>Message</h2>
<textarea name="comments" cols="" rows="" id="comments"></textarea>
</div>
<input name="Submit" type="submit" class="subbtn" value="Submit" />
<div id="message"></div>
</form>
</div>
</div>
Here is my PHP:
<?php
// Insert your email/web addresses and correct paths
$mailto = 'myemail#email.com' ;
$from = "http://website.com" ;
$formurl = "http://website.com/formmail.php" ;
$errorurl = "http://website.com/error.php" ;
$thankyouurl = "http://website.com/thankyou.php" ;
// Place Your Form info here...
$firstname = ($_POST['name']);
$email_from = ($_POST['email']);
$comments = ($_POST['comments']);
// Check If Empty
if (empty($firstname)) {
header( "Location: $errorurl" );
exit ;
}
// Add more Validation/Cleaning here...
// Place your Corresponding info here...
$message =
"Name: $firstname\n\n" .
"Email: $email_from\n\n" .
"Comment: $comments\n\n"
;
// Leave Alone
mail($mailto, $from, $message,
"From: \"$name\" <$email>" . $headersep . "Reply-To: \"$name\" <$email>" . $headersep );
header( "Location: $thankyouurl" );
exit ;
?>
Please let me know if you can assist me or need any other information from my html.
Thanks in advance!
To validate email in php, follow this link,
if (filter_var($email_from, FILTER_VALIDATE_EMAIL)) {
echo "This ($email_from) email address is considered valid.";
}
To hide the form, using jquery,
$(document).on('submit', '#ajaxsubmit',function(){
$(this).hide();
});
or using pure javascript,
Change HTML,
<form id="ajaxsubmit" action="formmail.php" method="post" onsubmit="myFunction()">
and JS
function myFunction(){
var form = document.getElementById("ajaxsubmit");
form.style.display = 'none';
}

Fadeout Email Form

I am attempting to have a bootstrap contact form fade out on submit.
I am working with code I have found (which I've slightly modified to suit my needs), and I am having trouble with its implementation. I'm fairly new and I seem to have gotten quite stuck.
Here is the JS:
$('contactUs').on('submit', function mailMe(form) {
form.preventDefault(); //Prevents default submit
var form = $(this);
var post_url = form.attr('action');
var post_data = form.serialize(); //Serialized the form data for process.php
$('#loader', form).html('<img src="http://domain.com/test/images/loading.gif" /> Please Wait...');
$.ajax({
type: 'POST',
url: 'http://domain.com/test/process.php', // Your form script
data: post_data,
success: function(msg) {
$(form).fadeOut(500, function(){
form.html(msg).fadeIn();
});
}
});
});
Here is the Form:
<form name="contactUs" onSubmit="return mailMe(this.form)" >
<div class="inputWrap">
<div class="fname">
<input class="myInput miLeft" type="text" placeholder="Name">
</div>
<div class="femail">
<input class="myInput miRight" type="text" placeholder="Email">
</div>
</div>
<div class="taWrap">
<textarea class="myTa" type="text" placeholder="Message"></textarea>
</div>
<button class="btns btn-3 btn-3g btnsx">Send</button>
</form>
And here is the process.php:
<?php
/* Configuration */
$subject = 'New Customer Email'; // Set email subject line here
$mailto = 'myemail#me.com'; // Email address to send form submission to
/* END Configuration */
$name = $_POST['name'];
$email = $_POST['email'];
$messageContent = $_POST['messageContent'];
$timestamp = date("F jS Y, h:iA.", time());
// HTML for email to send submission details
$body = "
<br>
<p>The following information was submitted through the contact form on your website:</p>
<p><b>Name</b>: $name<br>
<b>Email</b>: $email<br>
<b>Message</b>: $messageContent<br>
<p>This form was submitted on <b>$timestamp</b></p>
";
// Success Message
$success = "
<div class=\"row-fluid\">
<div class=\"span12\">
<h3>Submission successful</h3>
<p>Thank you for taking the time to contact Shaz Construction & Design. A representative will be in contact with you shortly. If you need immediate assistance or would like to speak to someone now, please feel free to contact us directly at <strong>(415) 382-8442</strong>.</p>
</div>
</div>
";
$headers = "From: $name <$email> \r\n";
$headers .= "Reply-To: $email \r\n";
$headers .= "MIME-Version: 1.0\r\n";
$headers .= "Content-Type: text/html; charset=ISO-8859-1\r\n";
$message = "<html><body>$body</body></html>";
if (mail($mailto, $subject, $message, $headers)) {
echo "$success"; // success
} else {
echo 'Form submission failed. Please try again...'; // failure
}
?>
There are a few small things you are missing:
Your jQuery selector for the form is incorrect - give your form an ID attribute of contactUs, and then use the selector $('form#contactUs'). Get rid of the name attribute on the form.
Your button element needs to be of type submit - your button currently does nothing.
You don't need the onSubmit attribute, you are already binding your form to an event in the JS.
Your input tags currently do not have any name elements on them - they are required - see http://api.jquery.com/serialize/
You try to access an attribute on the form that does not exist (action), but you don't use it, so just remove that line.
Use return false rather than preventDefault in your event handler (I couldn't get preventDefault to work. That might just be me though!)
I can't tell this because of the context of your code, but ensure that your JS is within a $('document').ready(function() { ... } block.
I think that your JS and HTML should be:
JS
$('form#contactUs').on('submit', function() {
var form = $(this);
var post_data = form.serialize(); //Serialized the form data for process.php
$('#loader').html('<img src="http://yasharsahaleh.com/test/images/loading.gif" /> Please Wait...');
$.ajax({
type: 'POST',
url: 'http://yasharsahaleh.com/test/process.php', // Your form script
data: post_data,
success: function(msg) {
$('#loader').html('');
// We know this is the form that needs fading in/out
$('form#contactUs').fadeOut(500, function(){
$('form#contactUs').html(msg).fadeIn();
});
}
});
return false;
});
HTML
<form id="contactUs">
<div class="inputWrap">
<div class="fname">
<input name="name" class="myInput miLeft" type="text" placeholder="Name">
</div>
<div class="femail">
<input name="email" class="myInput miRight" type="text" placeholder="Email">
</div>
</div>
<div class="taWrap">
<textarea name="messageContent" class="myTa" type="text" placeholder="Message"></textarea>
</div>
<button type="submit" class="btns btn-3 btn-3g btnsx">Send</button>
</form>
I made a small JSFiddle to illustrate most of this (taking out the AJAX part): http://jsfiddle.net/dualspiral/2rXas/1/
The PHP needs changing slightly, you are not actually printing out the variable contents. The body variable shoud actually be assigned:
$body = "
<br>
<p>The following information was submitted through the contact form on your website:</p>
<p><b>Name</b>: " . $name . "<br>
<b>Email</b>: " . $email . "<br>
<b>Message</b>: " . $messageContent . "<br>
<p>This form was submitted on <b>" . $timestamp . "</b></p>
";
and the last lines should read:
$headers = "From: " . $name . " <" . $email . "> \r\n";
$headers .= "Reply-To: " . $email . " \r\n";
$headers .= "MIME-Version: 1.0\r\n";
$headers .= "Content-Type: text/html; charset=ISO-8859-1\r\n";
$message = "<html><body>" . $body . "</body></html>";
if (mail($mailto, $subject, $message, $headers)) {
echo $success; // success
} else {
echo 'Form submission failed. Please try again...'; // failure
}
?>

Categories