Append PHP echo using jquery - javascript

I have PHP to validate a form, it echos and error message
<?php
if(!$_POST) exit;
error_reporting(0);
// Email address verification, do not edit.
function isEmail($email) {
return(preg_match("/^[-_.[:alnum:]]+#((([[:alnum:]]|[[:alnum:]][[:alnum:]-]*[[:alnum:]])\.)+(ad|ae|aero|af|ag|ai|al|am|an|ao|aq|ar|arpa|as|at|au|aw|az|ba|bb|bd|be|bf|bg|bh|bi|biz|bj|bm|bn|bo|br|bs|bt|bv|bw|by|bz|ca|cc|cd|cf|cg|ch|ci|ck|cl|cm|cn|co|com|coop|cr|cs|cu|cv|cx|cy|cz|de|dj|dk|dm|do|dz|ec|edu|ee|eg|eh|er|es|et|eu|fi|fj|fk|fm|fo|fr|ga|gb|gd|ge|gf|gh|gi|gl|gm|gn|gov|gp|gq|gr|gs|gt|gu|gw|gy|hk|hm|hn|hr|ht|hu|id|ie|il|in|info|int|io|iq|ir|is|it|jm|jo|jp|ke|kg|kh|ki|km|kn|kp|kr|kw|ky|kz|la|lb|lc|li|lk|lr|ls|lt|lu|lv|ly|ma|mc|md|mg|mh|mil|mk|ml|mm|mn|mo|mp|mq|mr|ms|mt|mu|museum|mv|mw|mx|my|mz|na|name|nc|ne|net|nf|ng|ni|nl|no|np|nr|nt|nu|nz|om|org|pa|pe|pf|pg|ph|pk|pl|pm|pn|pr|pro|ps|pt|pw|py|qa|re|ro|ru|rw|sa|sb|sc|sd|se|sg|sh|si|sj|sk|sl|sm|sn|so|sr|st|su|sv|sy|sz|tc|td|tf|tg|th|tj|tk|tm|tn|to|tp|tr|tt|tv|tw|tz|ua|ug|uk|um|us|uy|uz|va|vc|ve|vg|vi|vn|vu|wf|ws|ye|yt|yu|za|zm|zw)$|(([0-9][0-9]?|[0-1][0-9][0-9]|[2][0-4][0-9]|[2][5][0-5])\.){3}([0-9][0-9]?|[0-1][0-9][0-9]|[2][0-4][0-9]|[2][5][0-5]))$/i",$email));
}
if (!defined("PHP_EOL")) define("PHP_EOL", "\r\n");
$name = $_POST['name'];
$email = $_POST['email'];
$phone = $_POST['phone'];
$comments = $_POST['comments'];
$verify = $_POST['verify'];
$nameerror = 'please enter your name';
if(trim($name) == '') {
echo '<div class="error_name">Attention! You must enter your name.</div>';
exit();
} else if(trim($email) == '') {
echo '<div class="error_message"><br /><br /><center>Attention! Please enter a valid email address.</center></div>';
exit();
} else if(trim($phone) == '') {
echo '<div class="error_message"><br /><br /><center>Attention! Please enter a valid phone number.</center></div>';
exit();
} else if(!is_numeric($phone)) {
echo '<div class="error_message"><br /><br /><center>Attention! Phone number can only contain digits.</center></div>';
exit();
} else if(!isEmail($email)) {
echo '<div class="error_message"><br /><br /><center>Attention! You have enter an invalid e-mail address, try again.</center></div>';
exit();
}
else if(trim($comments) == '') {
echo '<div class="error_message"><br /><br /><center>Attention! Please enter your message.</center></div>';
exit();
}
if(get_magic_quotes_gpc()) {
$comments = stripslashes($comments);
}
// Configuration option.
// Enter the email address that you want to emails to be sent to.
// Example $address = "joe.doe#yourdomain.com";
$address = "cedrichugh#yahoo.com";
// Configuration option.
// i.e. The standard subject will appear as, "You've been contacted by John Doe."
// Example, $e_subject = '$name . ' has contacted you via Your Website.';
$e_subject = 'You\'ve been contacted by ' . $name . '.';
// Configuration option.
// You can change this if you feel that you need to.
// Developers, you may wish to add more fields to the form, in which case you must be sure to add them here.
$e_body = "You have been contacted by $name , their additional message is as follows." . PHP_EOL . PHP_EOL;
$e_content = "\"$comments\"" . PHP_EOL . PHP_EOL;
$e_reply = "You can contact $name via email, $email or via phone $phone";
$msg = wordwrap( $e_body . $e_content . $e_reply, 70 );
$headers = "From: Website_Contact_Form" . PHP_EOL;
$headers .= "Reply-To: $email" . PHP_EOL;
$headers .= "MIME-Version: 1.0" . PHP_EOL;
$headers .= "Content-type: text/plain; charset=utf-8" . PHP_EOL;
$headers .= "Content-Transfer-Encoding: quoted-printable" . PHP_EOL;
if(mail($address, $e_subject, $msg, $headers)) {
// Email has sent successfully, echo a success page.
echo "<fieldset>";
echo "<div id='success_page'>";
echo "<center><h1>Email Sent Successfully.</h1></center>";
echo "<center><p>Thank You <strong>$name</strong>, Your Message Has Been Sent. We Will Be In Contact With You Shortly.<br />Med Perfect</p></center>";
echo "</div>";
echo "</fieldset>";
} else {
echo 'ERROR!';
}
?>
But the DIV.error_name displays at the bottom of the page.
How can I append it to the input field so it can be displayed above or below it
<form role="form" id="feedbackForm" method="post" action="index.php?page=contact">
<div class="form-group">
<input type="text" class="form-control" id="name" name="name" placeholder="Name">
<span class="help-block" style="display:none;">Please enter your name.</span>
</div>
<div class="form-group">
<input type="phone" class="form-control" id="phone" name="phone" placeholder="Contact Number">
<span class="help-block" style="display: none;">Please enter a valid contact number address.</span>
</div>
<div class="form-group">
<input type="email" class="form-control" id="email" name="email" placeholder="Email Address">
<span class="help-block" style="display: none;">Please enter a valid e-mail address.</span>
</div>
<div class="form-group">
<select name="select" class="form-control" id="select">
<option value="">Please Select Your Interest</option>
<option value="general_enquiry">General Enquiry</option>
<option value="saab">Saab</option>
<option value="mercedes">Mercedes</option>
<option value="other">Other</option>
</select>
<span class="help-block" style="display: none;">Please enter a valid e-mail address.</span>
</div>
<div class="form-group">
<textarea rows="10" cols="100" class="form-control" id="comments" name="comments" placeholder="Message"></textarea>
<span class="help-block" style="display: none;">Please enter a message.</span>
</div>
<button type="submit" name="submit" id="feedbackSubmit" class="btn44 btn-4 btn-4c icon-mail-send" style="display: block; margin-top: 10px;">Send</button>
</form>
I have tried the following from api.jquery.com(I am a noob)
$( "#name" ).append( ".error_name" );

Create a JavaScript function that handles the updating of the DOM with the error message, and the function can be called from anywhere on the page. You'll be able to trigger the error messages wherever you want, including the HTML file, the JavaScript file, or on the PHP side.
Sample JS function:
function displayError(fieldID, errorClass, errorMessage) {
if ($('#' + fieldID).next('.' + errorClass).length == 0) {
$('#' + fieldID).after('<div class="' + errorClass + '">' + errorMessage + '</div>');
}
}
To call the JavaScript function (DOM must be ready):
displayError('name', 'error_name', 'You must enter your name.');
To control the calling of the function from PHP in your server-side validation:
if(trim($name) == '') {
// Call error message function after when DOM is ready
echo '<script>$(function () { displayError(\'name\', \'error_name\', \'You must enter your name.\'); });</script>';
exit();
}
You could also use the same function when validating on the JavaScript side:
$(function () {
$('#btnSubmit').on('click', function () {
event.preventDefault;
// Validate
if ($('#name').val() == '') {
// Name field is empty
displayError('name', 'error_name', 'You must enter your name.');
}
});
});
Demo: https://jsfiddle.net/BenjaminRay/6cLvnk3L/

How do you add the div to your site?
List of thoughts in order of preference.
You could leave an empty div (<div class"error_name"></div>) where you want the message to appear and add returned text to it (without the surrounding tags).
Instead of appending a string ".error_name", add the result of $(".error_name"). So $( "#name" ).after( $(".error_name") ); if the div is already added to the DOM. .append() adds it as a child of input.
You can also style and position the div with jquery and css without worrying about it's placement in DOM.

Related

Data from new HTML form input field not being passed to email using PHP and JavaScript

This is my first post on the site. I added a new input field to a previously working HTML contact form in order to collect the user’s street address. Although all other input fields continue to pass data to the email generated after the form is submitted, data is not being passed to the email with the street address. I have copied below the associated HTML, PHP, and JavaScript files, as well as an example of what data is now sent to the email.
I truly appreciate any help with what I am doing wrong. I have spent over 8 hours trying to solve this problem, but so far have been unsuccessful. Thank you!
Here is an example of the data now being placed into the email generated. Notice that the only data NOT being passed is the text that was input into the street address field of the contact form (blank).
Name: Tim Spyridon
Address:
Phone Number: 513-662-1464
Message:
Made major changes to PHP script. This may work!
Here is the HTML code used for the contact form:
<!-- Form Starts -->
<div id="contact_form">
<div class="form-group">
<label>Name <span class="required">*</span></label>
<input placeholder="Your Name" type="text" name="name" class="form-control input-field" required>
<label>Street Address and City <span class="required">*</span></label>
<input placeholder="Your Street Address and City" type="text" name="address" class="form-control input-field" required>
<label>Email Address <span class="required">*</span></label>
<input placeholder="Your Email Address" type="email" name="email" class="form-control input-field" required>
<label>Phone Number including Area Code <span class="required">*</span></label>
<input placeholder="Your 10-Digit Phone Number" type="tel" name="phone" class="form-control input-field" required>
<label>Message <span class="required">*</span></label>
<textarea placeholder="Type your message here ..." name="message" id="message" class="textarea-field form-control" rows="3" required></textarea>
</div>
<div class="text-right">
* Required Field
</div>
<button type="submit" id="submit_btn" value="Submit" class="btn center-block">Send message</button>
</div>
Here is my JavaScript code from a file called contact.js:
"use strict";
jQuery(document).ready(function($) {
$("#submit_btn").on("click", function() {
var proceed = true;
//simple validation at client's end
//loop through each field and we simply change border color to red for invalid fields
$("#contact_form input[required], #contact_form textarea[required]").each(function() {
$(this).css('background-color', '');
if (!$.trim($(this).val())) { //if this field is empty
$(this).css('background-color', '#FFDEDE'); //change border color to #FFDEDE
proceed = false; //set do not proceed flag
}
//check invalid email
var email_reg = /^([\w-\.]+#([\w-]+\.)+[\w-]{2,4})?$/;
if ($(this).attr("type") === "email" && !email_reg.test($.trim($(this).val()))) {
$(this).css('background-color', '#FFDEDE'); //change border color to #FFDEDE
proceed = false; //set do not proceed flag
}
});
if (proceed) //everything looks good! proceed...
{
//get input field values data to be sent to server
var post_data = {
'user_name': $('input[name=name]').val(),
'user_address': $('input[name=address]').val(),
'user_email': $('input[name=email]').val(),
'phone': $('input[name=phone]').val(),
'msg': $('textarea[name=message]').val()
};
//Ajax post data to server
$.post('php/sendmail.php', post_data, function(response) {
if (response.type === 'error') { //load json data from server and output message
var output = '<br><br><div class="error">' + response.text + '</div>';
} else {
var output = '<br><br><div class="success">' + response.text + '</div>';
//reset values in all input fields
$("#contact_form input, #contact_form textarea").val('');
}
$('html, body').animate({scrollTop: $("#contact_form").offset().top-50}, 2000);
$("#contact_results").hide().html(output).slideDown();
}, 'json');
}
});
//reset previously set border colors and hide all message on .keyup()
$("#contact_form input[required=true], #contact_form textarea[required=true]").keyup(function() {
$(this).css('background-color', '');
$("#result").slideUp();
});
});
Here is my PHP script from a file called sendmail.php:
<?php
if($_POST)
{
$to_email1 = "kim#twotailsup.com"; //Recipient email, Replace with own email here
$to_email2 = "tim#twotailsup.com"; //Recipient email, Replace with own email here
$email_subject = "Message from Website Contact Form";
//check if its an ajax request, exit if not
if(!isset($_SERVER['HTTP_X_REQUESTED_WITH']) AND strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) != 'xmlhttprequest') {
$output = json_encode(array( //create JSON data
'type'=>'error',
'text' => 'Sorry Request must be Ajax POST'
));
die($output); //exit script outputting json data
}
//Sanitize input data using PHP filter_var().
$user_name = filter_var($_POST["user_name"], FILTER_SANITIZE_STRING);
$user_address = filter_var($_POST['user_address'], FILTER_SANITIZE_STRING);
$user_email = filter_var($_POST["user_email"], FILTER_SANITIZE_EMAIL);
$phone = filter_var($_POST["phone"], FILTER_SANITIZE_NUMBER_INT);
$message = filter_var($_POST["msg"], FILTER_SANITIZE_STRING);
$message_body = "Name: " . $user_name . "\n"
. "Address: " . $user_address . "\n"
. "Email: " . $user_email . "\n"
. "Phone Number: " . $phone . "\n"
. "Message: " . "\n" . $message;
//proceed with PHP email.
$headers = 'From: '.$user_name.'' . "\r\n" .
'Reply-To: '.$user_email.'' . "\r\n" .
'X-Mailer: PHP/' . phpversion();
$send_mail = mail($to_email1, $email_subject, $message_body, $headers);
$send_mail = mail($to_email2, $email_subject, $message_body, $headers);
if(!$send_mail)
{
//If mail couldn't be sent output error. Check your PHP email configuration (if it ever happens)
$output = json_encode(array('type'=>'error', 'text' => '<p>Could not send mail! Please check your PHP mail configuration.</p>'));
die($output);
}else{
$output = json_encode(array('type'=>'message', 'text' => '<div class="alert alert-success" role="alert">
Hi '.$user_name .', Thank you for your message! We will get back to you soon.</div>'));
die($output);
}
}
?>
In support of the comment made last night (above ) here is the test version of the above script which appears to work perfectly well in terms of the newly added message field. There are comments at places where things were changed - some semantic, others functional.
<?php
if( $_POST ){
# Simple Boolean to switch between live & test mode
# whilst testing that this script does or does not
# function correctly.
$b_live=false;
$to_email1 = "kim#twotailsup.com"; //Recipient email, Replace with own email here
$to_email2 = "tim#twotailsup.com"; //Recipient email, Replace with own email here
$email_subject = "Message from Website Contact Form";
//check if its an ajax request, exit if not
if( !isset( $_SERVER['HTTP_X_REQUESTED_WITH'] ) AND strtolower( $_SERVER['HTTP_X_REQUESTED_WITH'] ) != 'xmlhttprequest' ) {
$output = json_encode(array( //create JSON data
'type'=>'error',
'text' => 'Sorry Request must be Ajax POST'
));
die($output); //exit script outputting json data
}
//Sanitize input data using PHP filter_var().
$user_name = filter_var($_POST["user_name"], FILTER_SANITIZE_STRING);
$user_address = filter_var($_POST['user_address'], FILTER_SANITIZE_STRING);
$user_email = filter_var($_POST["user_email"], FILTER_SANITIZE_EMAIL);
$phone = filter_var($_POST["phone"], FILTER_SANITIZE_NUMBER_INT);
$message = filter_var($_POST["msg"], FILTER_SANITIZE_STRING);
$message_body = "Name: " . $user_name . "\n"
. "Address: " . $user_address . "\n"
. "Email: " . $user_email . "\n"
. "Phone Number: " . $phone . "\n"
. "Message: " . "\n" . $message;
//proceed with PHP email.
$headers = 'From: '.$user_name.'' . "\r\n" .
'Reply-To: '.$user_email.'' . "\r\n" .
'X-Mailer: PHP/' . phpversion();
# If the script is live, attempt to send the emails
if( $b_live ){
$send_mail = mail($to_email1, $email_subject, $message_body, $headers);
$send_mail = mail($to_email2, $email_subject, $message_body, $headers);
}else{
# emulate either a success or failure randomly
# to aid testing of ajax callback
$send_mail=mt_rand(0,1);
# you can verify the message is being populated
$_POST['MESSAGE']=$message;
$_POST['TIME']=date( DATE_ATOM );
file_put_contents( __DIR__ . '/ajax.log', json_encode( $_POST ) . PHP_EOL, FILE_APPEND );
}
if(!$send_mail){
//If mail couldn't be sent output error. Check your PHP email configuration (if it ever happens)
$output = json_encode(array('type'=>'error', 'text' => '<p>Could not send mail! Please check your PHP mail configuration.</p>'));
die( $output );
}else{
$output = json_encode(array('type'=>'message', 'text' => '<div class="alert alert-success" role="alert">
Hi '.$user_name .', Thank you for your message! We will get back to you soon.</div>'));
die( $output );
}
}
?>
<!DOCTYPE html>
<html lang='en'>
<head>
<meta charset='utf-8' />
<script src='//code.jquery.com/jquery-latest.js'></script>
<title>Contact</title>
</head>
<body>
<!--
The `label` attribute **must** be associated with whichever form element
it is supposed to reference. This can be done either by including the
`for` attribute in the label with the input element's ID OR the form element
must be within the label itself - as shown below.
-->
<div id="contact_form">
<div class="form-group">
<label>
Name <span class="required">*</span>
<input placeholder="Your Name" type="text" name="name" class="form-control input-field" required />
</label>
<label>
Street Address and City <span class="required">*</span>
<input placeholder="Your Street Address and City" type="text" name="address" class="form-control input-field" required />
</label>
<label>
Email Address <span class="required">*</span>
<input placeholder="Your Email Address" type="email" name="email" class="form-control input-field" required />
</label>
<label>
Phone Number including Area Code <span class="required">*</span>
<input placeholder="Your 10-Digit Phone Number" type="tel" name="phone" class="form-control input-field" required />
</label>
<label>
Message <span class="required">*</span>
<textarea placeholder="Type your message here ..." name="message" id="message" class="textarea-field form-control" rows="3" required /></textarea>
</label>
</div>
<div class="text-right">
* Required Field
</div>
<button type="submit" id="submit_btn" value="Submit" class="btn center-block">Send message</button>
</div>
<!--
Added this DIV to allow output to be rendered
-->
<div id='contact_results'></div>
<script>
"use strict";
jQuery(document).ready(function($) {
$("#submit_btn").on("click", function() {
var proceed = true;
//simple validation at client's end
//loop through each field and we simply change border color to red for invalid fields
$("#contact_form input[required], #contact_form textarea[required]").each(function() {
$(this).css('background-color', '');
if (!$.trim($(this).val())) { //if this field is empty
$(this).css('background-color', '#FFDEDE'); //change border color to #FFDEDE
proceed = false; //set do not proceed flag
}
//check invalid email
var email_reg = /^([\w-\.]+#([\w-]+\.)+[\w-]{2,4})?$/;
if ($(this).attr("type") === "email" && !email_reg.test($.trim($(this).val()))) {
$(this).css('background-color', '#FFDEDE'); //change border color to #FFDEDE
proceed = false; //set do not proceed flag
}
});
if (proceed) //everything looks good! proceed...
{
//get input field values data to be sent to server
var post_data = {
'user_name': $('input[name=name]').val(),
'user_address': $('input[name=address]').val(),
'user_email': $('input[name=email]').val(),
'phone': $('input[name=phone]').val(),
'msg': $('textarea[name=message]').val()
};
//Ajax post data to server
/*
*****************************************************
This is the ONLY change made in the Javascript
*****************************************************
*/
const _URL=location.href; // 'php/sendmail.php'
$.post( _URL, post_data, function(response) {
if (response.type === 'error') { //load json data from server and output message
var output = '<br><br><div class="error">' + response.text + '</div>';
} else {
var output = '<br><br><div class="success">' + response.text + '</div>';
$("#contact_form input, #contact_form textarea").val('');
}
$('html, body').animate({scrollTop: $("#contact_form").offset().top-50}, 2000);
$("#contact_results").hide().html(output).slideDown();
}, 'json');
}
});
//reset previously set border colors and hide all message on .keyup()
$("#contact_form input[required=true], #contact_form textarea[required=true]").keyup(function() {
$(this).css('background-color', '');
$("#result").slideUp();
});
});
</script>
</body>
</html>
With this I could not replicate the issues stated in the question: The $message variable is populated and can be inspected in the console or the ajax.log file that is generated in test mode.

Stop contact form from replying in new tab. My OCD is fistfighting my ADD over contact form

this is my html, my php, and ajax for a contact form. It works great except it post the relpys in a new browser tab. I have spent hours trying to correct it. Please help.
html-
<!-- form fields -->
<form action="assets/php/contact.php" method="post" name="contactform" id="contactform" class=" animated out" data-animation="fadeInUp" data-delay="0">
<fieldset>
<div class="row">
<div class="col-md-6">
<div class="row">
<div class="col-sm-12">
<div class="form-group">
<input class="form-control" type="text" name="name" id="name" placeholder="Name">
</div>
</div>
<div class="col-sm-12">
<div class="form-group">
<input class="form-control" type="email" name="email" id="email" placeholder="Email">
</div>
</div>
<div class="col-sm-12">
<div class="form-group">
<input class="form-control" type="text" name="subject" id="subject" placeholder="Subject">
</div>
</div>
</div>
</div>
<div class="col-md-6">
<div class="form-group">
<textarea class="form-control" name="message" id="message" placeholder="Message..."></textarea>
</div>
</div>
</div>
</fieldset>
<!-- submit button -->
<div class="form-group">
<input type="submit" name="submit" value="Send message" id="submit" class="btn btn-sm btn-primary">
</div>
<div id="alert"></div>
</form>
PHP-
if(!$_POST) exit;
// Email address verification, do not edit.
function isEmail($email) {
return(preg_match("/^[-_.[:alnum:]]+#((([[:alnum:]]|[[:alnum:]][[:alnum:]-]*[[:alnum:]])\.)+(ad|ae|aero|af|ag|ai|al|am|an|ao|aq|ar|arpa|as|at|au|aw|az|ba|bb|bd|be|bf|bg|bh|bi|biz|bj|bm|bn|bo|br|bs|bt|bv|bw|by|bz|ca|cc|cd|cf|cg|ch|ci|ck|cl|cm|cn|co|com|coop|cr|cs|cu|cv|cx|cy|cz|de|dj|dk|dm|do|dz|ec|edu|ee|eg|eh|er|es|et|eu|fi|fj|fk|fm|fo|fr|ga|gb|gd|ge|gf|gh|gi|gl|gm|gn|gov|gp|gq|gr|gs|gt|gu|gw|gy|hk|hm|hn|hr|ht|hu|id|ie|il|in|info|int|io|iq|ir|is|it|jm|jo|jp|ke|kg|kh|ki|km|kn|kp|kr|kw|ky|kz|la|lb|lc|li|lk|lr|ls|lt|lu|lv|ly|ma|mc|md|me|mg|mh|mil|mk|ml|mm|mn|mo|mp|mq|mr|ms|mt|mu|museum|mv|mw|mx|my|mz|na|name|nc|ne|net|nf|ng|ni|nl|no|np|nr|nt|nu|nz|om|org|pa|pe|pf|pg|ph|pk|pl|pm|pn|pr|pro|ps|pt|pw|py|qa|re|ro|ru|rw|sa|sb|sc|sd|se|sg|sh|si|sj|sk|sl|sm|sn|so|sr|st|su|sv|sy|sz|tc|td|tf|tg|th|tj|tk|tm|tn|to|tp|tr|tt|tv|tw|tz|ua|ug|uk|um|us|uy|uz|va|vc|ve|vg|vi|vn|vu|wf|ws|ye|yt|yu|za|zm|zw)$|(([0-9][0-9]?|[0-1][0-9][0-9]|[2][0-4][0-9]|[2][5][0-5])\.){3}([0-9][0-9]?|[0-1][0-9][0-9]|[2][0-4][0-9]|[2][5][0-5]))$/i",$email));
}
if (!defined("PHP_EOL")) define("PHP_EOL", "\r\n");
$name = $_POST['name'];
$email = $_POST['email'];
$message = $_POST['message'];
if(trim($name) == '') {
echo '<div class="notification error clearfix"><p><strong>Attention!</strong> You must enter your name.</p></div>';
exit();
} else if(trim($email) == '') {
echo '<div class="notification error clearfix"><p><strong>Attention!</strong> Please enter a valid email address.</p></div>';
exit();
} else if(!isEmail($email)) {
echo '<div class="notification error clearfix"><p><strong>Attention!</strong> You have entered an invalid e-mail address, try again.</p></div>';
exit();
}
if(trim($message) == '') {
echo '<div class="notification error clearfix"><p><strong>Attention!</strong> Please enter your message.</p></div>';
exit();
}
if(get_magic_quotes_gpc()) {
$message = stripslashes($message);
}
// Configuration option.
// Enter the email address that you want to emails to be sent to.
// Example $address = "joe.doe#yourdomain.com";
$address = "your#email.com";
// Configuration option.
// i.e. The standard subject will appear as, "You've been contacted by John Doe."
// Example, $e_subject = '$name . ' has contacted you via Your Website.';
$e_subject = 'You\'ve been contacted by ' . $name . '.';
// Configuration option.
// You can change this if you feel that you need to.
// Developers, you may wish to add more fields to the form, in which case you must be sure to add them here.
$e_body = "You have been contacted by $name ." . PHP_EOL . PHP_EOL;
$e_content = "\"$message\"" . PHP_EOL . PHP_EOL;
$e_reply = "You can contact $name via email, $email";
$msg = wordwrap( $e_body . $e_content . $e_reply, 70 );
$headers = "From: $email" . PHP_EOL;
$headers .= "Reply-To: $email" . PHP_EOL;
$headers .= "MIME-Version: 1.0" . PHP_EOL;
$headers .= "Content-type: text/plain; charset=utf-8" . PHP_EOL;
$headers .= "Content-Transfer-Encoding: quoted-printable" . PHP_EOL;
if(mail($address, $e_subject, $msg, $headers)) {
// Email has sent successfully, echo a success page.
echo "<fieldset>";
echo "<div id='success_page'>";
echo "<div class='notification success clearfix'><p>Thank you <strong>$name</strong>, your message has been submitted to us.</p></div>";
echo "</div>";
echo "</fieldset>";
} else {
echo 'ERROR!';
}
JS-
/* ==============================================
Contact Form
=============================================== */
$('#contactform').submit(function(){
var action = $(this).attr('action');
$("#alert").slideUp(750,function() {
$('#alert').hide();
$('#submit')
.after('<img src="assets/images/ajax-loader.GIF" class="contactloader" />')
.attr('disabled','disabled');
$.post(action, {
name: $('#name').val(),
email: $('#email').val(),
message: $('#message').val()
},
function(data){
document.getElementById('alert').innerHTML = data;
$('#alert').slideDown('slow');
$('#contactform img.contactloader').fadeOut('slow',function(){$(this).remove();});
$('#submit').removeAttr('disabled');
if(data.match('success') !== null) {
$('#name').val('');
$('#email').val('');
$('#message').val('');
}
}
);
});
return false;
});
I want error or success messages to show on the contact.html page and not open a new browser tab.
Thank you advance for help restore my sanity.
Cheers
You just need to prevent the default form submit from firing, which will post the content to the URL in your form action.
$('#contactform').submit(function(event){
event.preventDefault();
...
});

PHP contact form bug

I have a contact form using html and i also have a sendEmail.php file.
Everything works on the front end and notified that the email has been sent but it never seems to come to my inbox.
I can't identify why this is happening?
Help is much appreciated.
Thanks in advance.
Here is HTML
<div class="form-field">
<input name="contactName" type="text" id="contactName" placeholder="Name" value="" minlength="2" required="">
</div>
<div class="row">
<div class="col-six tab-full">
<div class="form-field">
<input name="contactEmail" type="email" id="contactEmail" placeholder="Email" value="" required="">
</div>
</div>
<div class="col-six tab-full">
<div class="form-field">
<input name="contactSubject" type="text" id="contactSubject" placeholder="Subject" value="">
</div>
</div>
</div>
<div class="form-field">
<textarea name="contactMessage" id="contactMessage" placeholder="message" rows="10" cols="50" required=""></textarea>
</div>
<div class="form-field">
<button class="submitform">Submit</button>
<div id="submit-loader">
<div class="text-loader">Sending...</div>
<div class="s-loader">
<div class="bounce1"></div>
<div class="bounce2"></div>
<div class="bounce3"></div>
</div>
</div>
</div>
</form>
<!-- contact-warning -->
<div id="message-warning"></div>
<!-- contact-success -->
<div id="message-success">
<i class="fa fa-check"></i>Your message was sent, thank you!<br>
</div>
Here is the sendEmail.php
$siteOwnersEmail = 'info#jalina-digital.co.uk';
if($_POST) {
$name = trim(stripslashes($_POST['contactName']));
$email = trim(stripslashes($_POST['contactEmail']));
$subject = trim(stripslashes($_POST['contactSubject']));
$contact_message = trim(stripslashes($_POST['contactMessage']));
// Check Name
if (strlen($name) < 2) {
$error['name'] = "Please enter your name.";
}
// Check Email
if (!preg_match('/^[a-z0-9&\'\.\-_\+]+#[a-z0-9\-]+\.([a-z0-9\-]+\.)*+[a-z]{2}/is', $email)) {
$error['email'] = "Please enter a valid email address.";
}
// Check Message
if (strlen($contact_message) < 15) {
$error['message'] = "Please enter your message. It should have at least 15 characters.";
}
// Subject
if ($subject == '') { $subject = "Contact Form Submission"; }
// Set Message
$message .= "Email from: " . $name . "<br />";
$message .= "Email address: " . $email . "<br />";
$message .= "Message: <br />";
$message .= $contact_message;
$message .= "<br /> ----- <br /> This email was sent from your site's contact form. <br />";
// Set From: header
$from = $name . " <" . $email . ">";
// Email Headers
$headers = "From: " . $from . "\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";
if (!$error) {
ini_set("sendmail_from", $siteOwnersEmail); // for windows server
$mail = mail($siteOwnersEmail, $subject, $message, $headers);
if ($mail) { echo "OK"; }
else { echo "Something went wrong. Please try again."; }
} # end if - no validation error
else {
$response = (isset($error['name'])) ? $error['name'] . "<br /> \n" : null;
$response .= (isset($error['email'])) ? $error['email'] . "<br /> \n" : null;
$response .= (isset($error['message'])) ? $error['message'] . "<br />" : null;
echo $response;
} # end if - there was a validation error
}
?>
And here is some JS.
var ssContactForm = function() {
/* local validation */
$('#contactForm').validate({
/* submit via ajax */
submitHandler: function(form) {
var sLoader = $('#submit-loader');
$.ajax({
type: "POST",
url: "inc/sendEmail.php",
data: $(form).serialize(),
beforeSend: function() {
sLoader.fadeIn();
},
success: function(msg) {
// Message was sent
if (msg == 'OK') {
sLoader.fadeOut();
$('#message-warning').hide();
$('#contactForm').fadeOut();
$('#message-success').fadeIn();
}
// There was an error
else {
sLoader.fadeOut();
$('#message-warning').html(msg);
$('#message-warning').fadeIn();
}
},
error: function() {
sLoader.fadeOut();
$('#message-warning').html("Something went wrong. Please try again.");
$('#message-warning').fadeIn();
}
});
}
});
};
The code you have written has some errors.
1) In your HTML form it show <button class="submitform">Submit</button> you must just a name to that input example <input type="submit" name="send" class="submitform">Submit</input>
2) In your PHP sendEmail file if($_POST) must become if(isset($_POST['send']))
Accordingly making these corrections will solve. Also Note Sending mail in PHP will not instant receive msg this may take some time.

PHP contact form will just refresh the page after submission.

After searching for about 3 hours i still can't figure this one out.
I Have a html template with a contact form and im trying to make it work using a PHP script.
I changed the template to PHP and pasted the PHP form script in it. everything is working fine except the confirmation text.
After a successful submission it will just refresh the page instead of printing "Your mail has been sent successfuly ! Thank you for your feedback". i do not want a redirect, i just want it to print on the same page.
Any ideas?
I got a sample of my code.
<form action="<? echo $_SERVER['PHP_SELF']; ?>" id="contact-form" method="post" class="form afsana-form" role="form">
<div class="row">
<div class="col-sm-12 form-group">
<input class="form-control afsana-style" id="name" name="name" placeholder="name" type="text" required autofocus />
</div>
<div class="col-sm-12 form-group">
<input class="form-control afsana-style" id="email" name="email" placeholder="email" type="email" required />
</div>
<div class="col-sm-12 form-group">
<textarea class="form-control" id="message" name="message" placeholder="message" rows="5"></textarea>
</div>
<div class="col-sm-12 form-group">
<button class="btn btn-primary afsana-btn" name="submit" value="verzenden" type="submit">Verzenden <i class="ion-arrow-graph-up-right"></i></button>
</div>
</div>
</form>
<?php
if(isset($_POST["submit"])){
// Checking For Blank Fields..
if($_POST["name"]==""||$_POST["email"]==""||$_POST["message"]==""){
echo "Fill All Fields..";
}else{
// Check if the "Sender's Email" input field is filled out
$email=$_POST['email'];
// Sanitize E-mail Address
$email =filter_var($email, FILTER_SANITIZE_EMAIL);
// Validate E-mail Address
$email= filter_var($email, FILTER_VALIDATE_EMAIL);
if (!$email){
echo "Invalid Sender's Email";
}
else{
$subject = (Contact_form);
$message = $_POST['message'];
$headers = 'From:'. $email . "\r\n"; // Sender's Email
$headers .= 'Cc:'. $email2 . "\r\n"; // Carbon copy to Sender
// Message lines should not exceed 70 characters (PHP rule), so wrap it
$message = wordwrap($message, 70);
// Send Mail By PHP Mail Function
mail("something#domain.com", $subject, $message, $headers);
echo "Your mail has been sent successfuly ! Thank you for your feedback";
}
}
}
?>
First, you have this: $subject = (Contact_form); which should throw an error, so I assume you have error reporting turned off. When developing, you should have error reporting on so you can see errors in your code... Else you are just working blind. I don't mean by throwing tacky error_reporting(0) in every file either, I mean to set your error reporting level to E_ALL in your php.ini.
You also have: $headers .= 'Cc:'. $email2 . "\r\n";
However, $email2 is not defined anywhere, so you would get an error here too.. which is why it's important to test with error reporting on.
See if this works:
<?php
$error = '';
if(isset($_POST['submit']))
{
if ( !empty($_POST['name']) && !empty($_POST['email']) && !empty($_POST['message']) )
{
$email = $_POST['email'];
$email = filter_var($email, FILTER_SANITIZE_EMAIL);
if ( $email = filter_var($email, FILTER_VALIDATE_EMAIL) )
{
$subject = '(Contact_form)';
$message = $_POST['message'];
$headers = 'From:'. $email . "\r\n"; // Sender's Email
$message = wordwrap($message, 70);
if ( $result = mail("something#domain.com", $subject, $message, $headers) ) {
$error = 'Success';
} else {
$error = 'There was an error sending your email!';
}
} else {
$error = 'Invalid Email Address!';
}
} else {
$error = 'Please fill all fields.';
}
}
?>
<p><?= $error ?></p>
<form action="" method="post">
<input type="text" name="name" value="" /><br />
<input type="email" name="email" value="" /><br />
<textarea name="message" rows="5"></textarea><br />
<input type="submit" name="submit" value="submit" />
</form>
Try to put in $subject just a string value like:
$subject = 'Test subject';
change also the following line to this (there is no $email2 defined):
$headers .= 'Cc:'. $email . "\r\n"; // Carbon copy to Sender
and give it a try. You can also put as first line of your code
<?php error_reporting(E_ALL); ?>
and check for errors when submiting the form.

How to clear field after sending in an AJAX contact form?

First, the code:
CONTACT_FORM.HTML
<html>
<head>
<title>Contact Form</title>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<link rel="stylesheet" href="contact_form.css" />
<script src="contact_form.js"></script>
</head>
<body>
<div id="mainform">
<form id="form" name="form" action="contact_form.html">
<h3>Contact Form</h3>
<p id="returnmessage"></p>
<label>Name: <span>*</span></label>
<input type="text" id="name" placeholder="Name"/>
<label>Email: <span>*</span></label>
<input type="text" id="email" placeholder="Email"/>
<label>Contact No: <span>*</span></label>
<input type="text" id="contact" placeholder="10 digit Mobile no."/>
<label>Message:</label>
<textarea id="message" placeholder="Message......."></textarea>
<input type="button" id="submit" value="Send Message"/>
</form>
</div>
</body>
</html>
CONTACT_FORM.PHP
<?php
$name = $_POST['name1'];
$email = $_POST['email1'];
$message = $_POST['message1'];
$contact = $_POST['contact1'];
$email = filter_var($email, FILTER_SANITIZE_EMAIL);
if (filter_var($email, FILTER_VALIDATE_EMAIL)) {
if (!preg_match("/^[0-9]{10}$/", $contact)) {
echo "<span>* Please Fill Valid Contact No. *</span>";
} else {
$subject = "Message from website...";
$headers = 'MIME-Version: 1.0' . "\r\n";
$headers .= 'Content-type: text/html; charset=iso-8859-1' . "\r\n";
$headers .= 'From:' . $email. "\r\n";
$headers .= 'Cc:' . $email. "\r\n";
$template = '<div style="padding:50px; color:white;">Hello ' . $name . ',<br/>'
. '<br/>Thank you for contacting us.<br/><br/>'
. 'Name: ' . $name . '<br/>'
. 'Email: ' . $email . '<br/>'
. 'Contact No: ' . $contact . '<br/>'
. 'Message: ' . $message . '<br/><br/>'
. 'This is a contact confirmation email.'
. '<br/>'
. 'We will keep you posted with our goings on.</div>';
$sendmessage = "<div style=\"background-color:#7E7E7E; color:white;\">" . $template . "</div>";
$sendmessage = wordwrap($sendmessage, 70);
mail("me#mydomain.com", $subject, $sendmessage, $headers);
echo "Thank you, your query has been received.";
}
} else {
echo "<span>* invalid email *</span>";
}
?>
CONTACT_FORM.JS
$(document).ready(function() {
$("#submit").click(function() {
var name = $("#name").val();
var email = $("#email").val();
var message = $("#message").val();
var contact = $("#contact").val();
$("#returnmessage").empty();
if (name == '' || email == '' || contact == '') {
alert("Please Fill Required Fields");
} else {
$.post("contact_form.php", {
name1: name,
email1: email,
message1: message,
contact1: contact
}, function(data) {
$("#returnmessage").append(data);
if (data == "Your Query has been received, We will contact you soon.") {
// $("#form")[0].reset();
$('#form').find('form')[0].reset();
}
});
}
});
});
My questions are these...
How can I clear the form following submission?
Why is the CC back to the sender not functioning?
Thanks in advance.
As for the reset your code is trying to look inside one form to find another form ... that doesn't exist
Change
$('#form').find('form')[0].reset();
To
$('#form')[0].reset();
Here's a way to clear the form from the top of my head:
In your HTML, add
<input type="reset" style="display:none;" id="reset-button" />
Then, in your JS:
if (data == "Your Query has been received, We will contact you soon.") {
$('#reset-button').click();
}
About the CC part, why don't you use PHPMailer, it'll reduce your effort and be a lot easier to send to many recipients.
Thanks to charlietfl for pointing out the difference the text for the IF logic. Everything is working fine and dandy now.
As per charlietfl's suggestion, I changed the following line in my JS file:
OLD CODE: $('#form').find('form')[0].reset();
NEW CODE: $('#form')[0].reset();
Also, I modified the message text to be the same in the PHP and the JS so the IF statement would validate.
Thanks again!
You can clear all text input elements.
$( "#form input:text" ).attr({value: ""});
Or to reset each field to the placeholder value:
$( "#form input:text" ).each(function(){
var placeholder_value = $(this).attr('placeholder');
$(this).attr('value', placeholder_value});
});

Categories

Resources