php simple contact form - stop submit on page refresh - javascript

The following PHP form works without any issues other than on refresh. If a user hits the refresh button after submitting the form, it re-submits the form.
Is there a way to use PHP or Jquery to stop the form re-submitting after refreshing the page?
I know in PHP there should be a way with Session, but I am not sure how.
contact.php
<script src="http://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<style>
.error_message{color:#cc0000;}
.form1{}
.form2{display:none;}
#succsess_page h1{background:url('http://example.com/ok.png')left no-repeat;padding-left:40px;color:#45a015; }
</style>
<h1>This is a simple contact form</h1>
<?php
//fields
$link_address = 'contact.php'; // page to redirect to
$honeypot = '';
$error = '';
$name = 'Name';
$email = 'Email';
$comments = 'Message';
if(isset($_POST['contactus'])) {
$honeypot = $_POST['email_confirm'];
$name = $_POST['name'];
$email = $_POST['email'];
$comments = $_POST['comments'];
// honeypot
if($honeypot)
exit(1);
//error messages
if(trim($name) == 'Name') {
$error = '<div class="error_message">Need your Name</div>';
} else if(trim($name) == '') {
$error = '<div class="error_message">Need your Name</div>';
} else if(trim($email) == 'Email') {
$error = '<div class="error_message">Need your Email</div>';
} else if(trim($email) == '') {
$error = '<div class="error_message">Need your Email</div>';
} else if(!isEmail($email)) {
$error = '<div class="error_message">Need a valid email</div>';
} else if(trim($comments) == 'Message') {
$error = '<div class="error_message">A Message is required</div>';
} else if(trim($comments) == '') {
$error = '<div class="error_message">A Message is required</div>';
}
if($error == '') {
if(get_magic_quotes_gpc()) {
$comments = stripslashes($comments);
}
//email address
$address = "email#example.com";
//email message
$e_subject = 'Web Message from: ' . $name . '.';
$e_body = "From: $name\nEmail: $email \r\n\nMessage:\n$comments\n\n\n";
$msg = $e_body . $e_content . $e_reply;
if(mail($address, $e_subject, $msg, "From: $email\r\nReply-To: $email\r\nReturn-Path: $email\r\n"))
{
//success html page response
echo "<div id='succsess_page'>";
echo "<h1>Email Sent Successfully.</h1>";
echo "<p>Thank you. The following was sent to us. <br/><br/>$name<br/><br/>$email<br/><br/>$comments</p>";
echo "<a href='$link_address'>CLOSE THIS MESSAGE</a>";
echo "</div>";
} else echo "Error. Mail not sent";
}
}
if(!isset($_POST['contactus']) || $error != '') // Do not edit.
{
?>
<?php echo $error; ?>
<!--form-->
<form method="post" action="" id="myform">
<p class="form1">Name: <input name="name" type="text" id="name" size="30" class="input1" value="<?php echo $name; ?>" onfocus="if(this.value == 'Name') { this.value = ''; }" onblur="toUpper(this.value); if(this.value == '') { this.value = 'Name'; }" value="Name" /></p>
<p class="form1">Email: <input name="email" type="text" id="email" size="30" class="input2" value="<?php echo $email; ?>" onfocus="if(this.value == 'Email') { this.value = ''; }" onblur="if(this.value == '') { this.value = 'Email'; }" value="Email" /></p>
<p class="form2">Confirm Email: <input name="email_confirm" type="text" id="email_confirm" size="30" value="<?php echo $email_confirm; ?>" /></p>
<p class="form1">Message: <textarea name="comments" cols="40" rows="3" id="comments" value="<?php echo $comments; ?>" onfocus="if(this.value == 'Message') { this.value = ''; }" onblur="if(this.value == '') { this.value = 'Message'; }" value="Message"><?php echo $comments; ?></textarea></p>
<p class="form1"><input name="contactus" type="submit" class="submit" id="contactus" value="Submit" /></p>
</form>
<!--end form-->
<?php }
function isEmail($email) { // Email address verification, do not edit.
return(preg_match("/^[_a-z0-9-]+(\.[_a-z0-9-]+)*#[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,12})$/",$email));
}
?>
<!------- capitalize first letter Name input ---->
<script>
function toUpper(mystring) {
var sp = mystring.split(' ');
var wl=0;
var f ,r;
var word = new Array();
for (i = 0 ; i < sp.length ; i ++ ) {
f = sp[i].substring(0,1).toUpperCase();
r = sp[i].substring(1);
word[i] = f+r;
}
newstring = word.join(' ');
document.getElementById('name').value = newstring;
return true;
}
</script>

After the form has been submitted correctly run the following code:
header("Location :contact.php?msg=success");
This will redirect the user back to the contact form with an condition allowing for a message to be displayed.
if($_REQUEST['msg']){
echo "Contact Form Submitted Successfully!!";
}
If they hit refresh it will just bring up a successful message while displaying the contact form again.
Update:
if(mail($address, $e_subject, $msg, "From: $email\r\nReply-To: $email\r\nReturn-Path: $email\r\n"))
{
header("Location: contact.php?msg=success");
}else{
header("Location: contact.php?msg=error");
}
Then for displaying:
<?php if($_REQUEST['msg']=="success"){
echo "Success Message Here.";
}elseif($_REQUEST['msg']=="error"){
echo "Error Message Here."
}
<!--form-->
<form method="post" action="" id="myform">

Related

Ajax : one ajax request for another forms

I have 3 contact form in one page (header, page, footer). How i can create one ajax request for all form ? I want when user click each one form send data fron only this form. Just now send from all forms. I used hasClass for determining from which class sending data, but i can't it
HTML:
<form id="contact-form1" method="POST" class="d-flex form">
<input type="text" class="simple-input" id="name" placeholder="Name">
<input type="text" class="simple-input" id="email" placeholder="Email address">
<textarea class="quession-input" id="msg" placeholder="Your question"></textarea>
<div class="checkboks custom-sq">
<input type="checkbox" class="checked-checkbox" name="myCheckboxes[]" id="box1" checked="checked" value="true" />
<label for="box1" class="checkboks-text"><?php echo the_field('checkbox_text', 'option'); ?></label>
</div>
<button type="submit" id="submit" class="danger-btn submit1"><?php echo the_field('btn_send', 'option'); ?></button>
</form>
<form id="contact-form" method="POST" class="d-flex form">
<input type="text" class="simple-input" id="hy_name" placeholder="Name">
<input type="text" class="simple-input" id="hy_email" placeholder="Email address">
<textarea class="quession-input" id="hy_msg" placeholder="Your question"></textarea>
<div class="checkboks custom-sq">
<input type="checkbox" id="box3" class="checked-checkbox" checked="checked" />
<label for="box3" class="checkboks-text"><?php echo the_field('checkbox_text', 'option'); ?></label>
</div>
<button type="submit" id="submit" class="danger-btn hy-submit submit2"><?php echo the_field('btn_send', 'option'); ?></button>
</form>
Ajax:
jQuery('.submit, .hy-submit').on('click', function(e) {
e.preventDefault();
// All data from form
var str = $(this).closest('form').serialize();
// Get current page url
var page_url = window.location.toString();
// Vars
var name = jQuery('#name').val();
var hy_name = jQuery('#hy_name').val();
var email = jQuery('#email').val();
var hy_email = jQuery('#hy_email').val();
var msg = jQuery('#msg').val();
var hy_msg = jQuery('#hy_msg').val();
var subj = jQuery('#subj').val();
var obj=$(this);
if($(obj).hasClass('hy-submit')){
validatehyEmail(hy_email);
if (hy_msg == '' || hy_email == '' || validatehyEmail(jQuery('#hy_email').val()) == false) {
validatehyEmail(hy_email);
validateText(jQuery('#hy_msg'));
validateText(jQuery('#hy_name'));
return false;
}
console.log('submit');
} else if ($(obj).hasClass('submit')) {
validateEmail(email);
if (msg == '' || email == '' || validateEmail(jQuery('#email').val()) == false) {
validateEmail(email);
validateText(jQuery('#msg'));
validateText(jQuery('#name'));
return false;
}
console.log('submit');
}
// Get checkbox value
var chkElem = document.getElementsByName("myCheckboxes[]");
var choice ="";
for(var i=0; i< chkElem.length; i++)
{
if(chkElem[i].checked)
choice = choice + chkElem[i].value;
}
jQuery.ajax({
type: "post",
url: ajaxactionurl,
data: "action=send_email&" + str + "&myCheckboxes=" + choice + "&url=" + page_url,
success: function (response) {
jQuery('#contact-form input').val('');
jQuery('#contact-form textarea').val('');
jQuery('.submit').text('Done!');
},
error: function (jqXHR, textStatus, errorThrown) {
console.log(textStatus);
}
});
});
PHP:
add_action('wp_ajax_nopriv_send_email', 'send_email');
add_action('wp_ajax_send_email', 'send_email');
function send_email() {
$checkbox = $_POST['myCheckboxes'];
if (isset($checkbox)) {
echo $checkbox;
}
$headers = 'Content-Type: text/html; charset="utf-8"';
$name = $_POST['name'];
$url = $_POST['url'];
$hy_name = $_POST['hy_name'];
$from = 'contact#test.com';
$to = 'test#test.com';
$email = $_POST['email'];
$hy_email = $_POST['hy_email'];
$msg = $_POST['msg'];
$hy_msg = $_POST['hy_msg'];
$subject = 'Footer form: ' . $_POST['email'];
$message .= (!empty($name)) ? '<p><strong>User Name</strong> : ' . $name .' </p>' : '';
$message .= (!empty($email)) ? '<p><strong>User Email</strong> : '. $email .'</p>' : '';
$message .= (!empty($msg)) ? '<p><strong>User Message</strong> : '.$msg .'</p>' : '';
$message .= (!empty($checkbox)) ? '<p><strong>Checkboxs</strong> : '.$checkbox .'</p>' : '';
$message .= (!empty($url)) ? '<p><strong>Url:</strong> : '.$url .'</p>' : '';
$message .= (!empty($hy_name)) ? '<p><strong>User Name</strong> : '.$hy_name .'</p>' : '';
$message .= (!empty($hy_email)) ? '<p><strong>User Email</strong> : '.$hy_email .'</p>' : '';
$message .= (!empty($hy_msg)) ? '<p><strong>User Message</strong> : '.$hy_msg .'</p>' : '';
$message .= '</body></html>';
echo mail($to, $subject, $message, $headers);
return $msg;
die();
}
Use form id attribute and use preventDefault method to prevent the forms from submitting.
$('#form-id').preventDefault();

Php and Ajax email form

i am totally new to ajax and just started getting a hang of php. So i got a ajax and php email code online that seemed to work on the first try and next few days suddenly kept returning with the error message which is "something went wrong". Please i'd appreciate if i could be put through on the source of this and how i could fix it. Thanks much
JS
$("#contactForm").validator().on("submit", function (event) {
if (event.isDefaultPrevented()) {
// handle the invalid form...
formError();
submitMSG(false, "Did you fill in the form properly?");
} else {
// everything looks good!
event.preventDefault();
submitForm();
}
});
function submitForm(){
// Initiate Variables With Form Content
var name = $("#name").val();
var email = $("#email").val();
var msg_subject = $("#msg_subject").val();
var message = $("#message").val();
$.ajax({
type: "POST",
url: "php/form-process.php",
data: "name=" + name + "&email=" + email + "&msg_subject=" + msg_subject + "&message=" + message,
success : function(text){
if (text == "success"){
formSuccess();
} else {
formError();
submitMSG(false,text);
}
}
});
}
function formSuccess(){
$("#contactForm")[0].reset();
submitMSG(true, "Message Submitted!")
}
function formError(){
$("#contactForm").removeClass().addClass('shake animated').one('webkitAnimationEnd mozAnimationEnd MSAnimationEnd oanimationend animationend', function(){
$(this).removeClass();
});
}
function submitMSG(valid, msg){
if(valid){
var msgClasses = "h3 text-center tada animated text-success";
} else {
var msgClasses = "h3 text-center text-danger";
}
$("#msgSubmit").removeClass().addClass(msgClasses).text(msg);
}
HTML
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form id="contactForm">
<div class="row">
<div class="col-md-12">
<div class="form-group">
<input type="text" class="form-control" id="name" placeholder="Full Name" name="name" data-error="Please input your full name" required>
<div class="help-block with-errors"></div>
</div>
</div>
<div class="col-md-12">
<div class="form-group">
<input type="text" class="form-control" id="email" placeholder="Your Email" name="name" data-error="Please input your email" required>
<div class="help-block with-errors"></div>
</div>
</div>
<div class="col-md-12">
<div class="form-group">
<textarea class="form-control" id="message" placeholder="Your Message" rows="8" data-error="Write your message" required></textarea>
<div class="help-block with-errors"></div>
</div>
<div class="submit-button text-center">
<button class="btn btn-common" id="submit" type="submit">Send Message</button>
<div id="msgSubmit" class="h3 text-center hidden"></div>
<div class="clearfix"></div>
</div>
</div>
</div>
</form>
PHP
<?php
$errorMSG = "";
// NAME
if (empty($_POST["name"])) {
$errorMSG = "Name is required ";
} else {
$name = $_POST["name"];
}
// EMAIL
if (empty($_POST["email"])) {
$errorMSG .= "Email is required ";
} else {
$email = $_POST["email"];
}
// MSG SUBJECT
if (empty($_POST["msg_subject"])) {
$errorMSG .= "Subject is required ";
} else {
$msg_subject = $_POST["msg_subject"];
}
// MESSAGE
if (empty($_POST["message"])) {
$errorMSG .= "Message is required ";
} else {
$message = $_POST["message"];
}
$EmailTo = "name#email.com";
$Subject = "New Message Received";
// prepare email body text
$Body = "";
$Body .= "Name: ";
$Body .= $name;
$Body .= "\n";
$Body .= "Email: ";
$Body .= $email;
$Body .= "\n";
$Body .= "Subject: ";
$Body .= $msg_subject;
$Body .= "\n";
$Body .= "Message: ";
$Body .= $message;
$Body .= "\n";
// send email
$success = mail($EmailTo, $Subject, $Body, "From:".$email);
// redirect to success page
if ($success && $errorMSG == ""){
echo "success";
}else{
if($errorMSG == ""){
echo "Something went wrong :("; //-->this is the error i get
} else {
echo $errorMSG;
}
}
?>
your logic is backwards, in your code an empty $errorMSG is good.
if($errorMSG != ""){ // if NOT empty
echo "Something went wrong: ".$errorMSG;
}else{
//good
}

Submit Contact Form w/o Reloading Page Using Ajax

I am following a guide to build a bootstrap contact form and submit it through mail.php without having to reload the page using ajax. I am able to get the form to work up until I try implementing ajax. I get stuck because the instructions arent clear as to which code exactly needs to be replaced and where the new code is supposed to go. Here is a link to the guide I am following and the section I am stuck at:
Sending email without reloading page using AJAX
This is the site I am trying to get it to work on: CRANE TECH. NET
I am not so familiar with php so I'm thinking that is where I am messing it up at.
Here is the exact code I am using:
HTML
<section class="section">
<h2 class="section-heading text-muted h4 pt-4">Free Consultation</h2>
<!--CONTACT DESCRIPTION-->
<p class="section-description">Are you ready to turn your vision into a reality? Fill out the contact form below and a member of our team will get back to you as soon as possible. Let's bring your idea to life!</p>
<div class="row">
<div class="col-12">
<form id="contact-form" name="contact-form" action="mail.php" method="POST">
<div class="row">
<!--NAME INPUT-->
<div class="col-12">
<div class="md-form">
<input type="text" id="name" name="name" class="form-control" placeholder="* NAME" required>
<label for="name" class=""></label>
</div>
</div>
<!--EMAIL INPUT-->
<div class="col-12">
<div class="md-form">
<input type="text" id="email" name="email" class="form-control" placeholder="* EMAIL" required>
<label for="email" class=""></label>
</div>
</div>
</div>
<div class="row">
<!-- PHONE NUMBER INPUT -->
<div class="col-12">
<div class="md-form">
<input type="text" id="clientPhone" name="clientPhone" class="form-control" placeholder="PHONE" required>
<label for="phone number" class=""></label>
</div>
</div>
<!--SUBJECT INPUT-->
<div class="col-12">
<div class="md-form">
<input type="text" id="subject" name="subject" class="form-control" placeholder="* SUBJECT" required>
<label for="subject" class=""></label>
</div>
</div>
</div>
<div class="row">
<!--MESSAGE INPUT-->
<div class="col-12">
<div class="md-form">
<textarea type="text" id="message" name="message" rows="3" class="form-control md-textarea" placeholder="* MESSAGE" required></textarea>
<label for="message"></label>
</div>
</div>
</div>
</form>
<!-- SUBMIT BUTTON -->
<div class=" col-3 offset-3 offset-md-4 mb-4">
<button class="btn btn-warning" onclick="validateForm()">Send <i class="fa fa-paper-plane ml-1"></i></button>
</div>
<div id="status" class="text-muted col-12 col-md-8 offset-md-2 my-1"></div>
</div>
JS
function validateForm() {
var name = document.getElementById('name').value;
if (name == "") {
document.getElementById('status').innerHTML = "Name cannot be empty";
return false;
}
var email = document.getElementById('email').value;
if (email == "") {
document.getElementById('status').innerHTML = "Email cannot be empty";
return false;
} else {
var re = /^(([^<>()\[\]\\.,;:\s#"]+(\.[^<>()\[\]\\.,;:\s#"]+)*)|(".+"))#((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
if (!re.test(email)) {
document.getElementById('status').innerHTML = "Email format invalid";
return false;
}
}
var subject = document.getElementById('subject').value;
if (subject == "") {
document.getElementById('status').innerHTML = "Subject cannot be empty";
return false;
}
var message = document.getElementById('message').value;
if (message == "") {
document.getElementById('status').innerHTML = "Message cannot be empty";
return false;
}
document.getElementById('status').innerHTML = "Sending...";
formData = {
'name': $('input[name=name]').val(),
'email': $('input[name=email]').val(),
'clientPhone': $('input[name=clientPhone]').val(),
'subject': $('input[name=subject]').val(),
'message': $('textarea[name=message]').val()
};
document.getElementById('contact-form').submit();
$.ajax({
url: "mail.php",
type: "POST",
data: formData,
success: function(data, textStatus, jqXHR) {
$('#status').text(data.message);
if (data.code) //If mail was sent successfully, reset the form.
$('#contact-form').closest('form').find("input[type=text], textarea").val("");
},
error: function(jqXHR, textStatus, errorThrown) {
$('#status').text(jqXHR);
}
});
}
MAIL.PHP
<?php
if(isset( $_POST['name']))
$name = $_POST['name'];
if(isset( $_POST['email']))
$email = $_POST['email'];
if(isset( $_POST['clientPhone']))
$clientPhone = $_POST['clientPhone'];
if(isset( $_POST['subject']))
$subject = $_POST['subject'];
if(isset( $_POST['message']))
$message = $_POST['message'];
$name = $_POST['name'];
$email = $_POST['email'];
$clientPhone = $_POST['clientPhone']
$message = $_POST['message'];
$subject = $_POST['subject'];
header('Content-Type: application/json');
if ($name === ''){
print json_encode(array('message' => 'Name cannot be empty', 'code' => 0));
exit();
}
if ($email === ''){
print json_encode(array('message' => 'Email cannot be empty', 'code' => 0));
exit();
} else {
if (!filter_var($email, FILTER_VALIDATE_EMAIL)){
print json_encode(array('message' => 'Email format invalid.', 'code' => 0));
exit();
}
}
if ($subject === ''){
print json_encode(array('message' => 'Subject cannot be empty', 'code' => 0));
exit();
}
if ($message === ''){
print json_encode(array('message' => 'Message cannot be empty', 'code' => 0));
exit();
}
// if ($name === ''){
// echo "Name cannot be empty.";
// echo "<br>";
// echo "<br>";
// echo "<a href='index.html'>GO BACK</a>";
// die();
// }
// if ($email === ''){
// echo "Email cannot be empty.";
// echo "<br>";
// echo "<br>";
// echo "<a href='index.html'>GO BACK</a>";
// die();
// } else {
// if (!filter_var($email, FILTER_VALIDATE_EMAIL)){
// echo "Email format invalid.";
// echo "<br>";
// echo "<br>";
// echo "<a href='index.html'>GO BACK</a>";
// die();
// }
// }
// if ($subject === ''){
// echo "Subject cannot be empty.";
// echo "<br>";
// echo "<br>";
// echo "<a href='index.html'>GO BACK</a>";
// die();
// }
// if ($message === ''){
// echo "Message cannot be empty.";
// echo "<br>";
// echo "<br>";
// echo "<a href='index.html'>GO BACK</a>";
// die();
// }
$content="From: $name \n Email: $email \n Phone #: $clientPhone \n Subject: $subject \n Message: $message";
$recipient = "support#crane-tech.net";
$mailheader = "From: $email \r\n";
mail($recipient, $subject, $content, $mailheader) or die("Error!");
print json_encode(array('message' => 'Email successfully sent!', 'code' => 1));
exit();
?>
Main Issue
You main issue is that there is a missing semcolon (;) and the end of line 15 in the php code.
Other Issues
Your website is using JQuery Slim, $.ajax is not included in the slim version so you are getting an error due to that. To fix this just include the full JQuery or do the ajax without JQuery.
You may also want to get rid of this line:
document.getElementById('contact-form').submit();
because it is causing a redirect when you are already manually submitting your data.
You should remove these lines because you have already set them:
$name = $_POST['name'];
$email = $_POST['email'];
$clientPhone = $_POST['clientPhone']
$message = $_POST['message'];
$subject = $_POST['subject'];
Unrelated note:
If you are already using JQuery, you should be using it - instead of doing this:
document.getElementById('status')
You should be using:
$('#status')

php code inside html in Asp.net mvc remains as it when run

I use Asp.net mvc 5 with c# in Visual Studio 2017, I want to add contact form and the code of the contact contains part in php, javascript and html
the problem is when I run the page in browser it display the contact form from html and javascript but it leaves the php code written in as it. I means it display lines of php code in the page.
How can I solve this problem?
$('.contact-form form input[type="text"], .contact-form form textarea').on('focus', function () {
$('.contact-form form input[type="text"], .contact-form form textarea').removeClass('input-error');
});
$('.contact-form form').submit(function (e) {
e.preventDefault();
$('.contact-form form input[type="text"], .contact-form form textarea').removeClass('input-error');
var postdata = $('.contact-form form').serialize();
$.ajax({
type: 'POST',
url: 'assets/contact.php',
data: postdata,
dataType: 'json',
success: function (json) {
if (json.nameMessage != '') {
$('.contact-form form .contact-name').addClass('input-error');
}
if (json.emailMessage != '') {
$('.contact-form form .contact-email').addClass('input-error');
}
if (json.subjectMessage != '') {
$('.contact-form form .contact-subject').addClass('input-error');
}
if (json.messageMessage != '') {
$('.contact-form form textarea').addClass('input-error');
}
if (json.nameMessage == '' && json.emailMessage == '' && json.subjectMessage == '' && json.messageMessage == '') {
$('.contact-form form').fadeOut('fast', function () {
$('.contact-form').append('Thanks for contacting us! We will get back to you very soon.');
// reload background
$.backstretch("resize");
});
}
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form role="form" action="assets/contact.php" method="post">
<div class="form-group">
<label class="sr-only" for="contact-name">Name</label>
<input type="text" name="name" placeholder="Name..." class="contact-name form-control" id="contact-name">
</div>
<div class="form-group">
<label class="sr-only" for="contact-email">Email</label>
<input type="text" name="email" placeholder="Email..." class="contact-email form-control" id="contact-email">
</div>
<div class="form-group">
<label class="sr-only" for="contact-subject">Subject</label>
<input type="text" name="subject" placeholder="Subject..." class="contact-subject form-control" id="contact-subject">
</div>
<div class="form-group">
<label class="sr-only" for="contact-message">Message</label>
<textarea name="message" placeholder="Message..." class="contact-message form-control" id="contact-message"></textarea>
</div>
<button type="submit" class="btn">Send message</button>
</form>
<?php
// Email address verification
function isEmail($email) {
return filter_var($email, FILTER_VALIDATE_EMAIL);
}
if($_POST) {
// Enter the email where you want to receive the message
$emailTo = 'kk#gmail.com';
$name = addslashes(trim($_POST['name']));
$clientEmail = addslashes(trim($_POST['email']));
$subject = addslashes(trim($_POST['subject']));
$message = addslashes(trim($_POST['message']));
$array = array('nameMessage' => '', 'emailMessage' => '', 'subjectMessage' => '', 'messageMessage' => '');
if($name == '') {
$array['nameMessage'] = 'Empty name!';
}
if(!isEmail($clientEmail)) {
$array['emailMessage'] = 'Invalid email!';
}
if($subject == '') {
$array['subjectMessage'] = 'Empty subject!';
}
if($message == '') {
$array['messageMessage'] = 'Empty message!';
}
if($name != '' && isEmail($clientEmail) && $subject != '' && $message != '') {
// Send email
$message = "Message from: " . $name . "\r\n" . $message;
$headers = "From: " . $clientEmail . " <" . $clientEmail . ">" . "\r\n" . "Reply-To: " . $clientEmail;
mail($emailTo, $subject . " (bootstrap contact form)", $message, $headers);
}
echo json_encode($array);
}
?>

Ajax script not calling

Inside my page it works, doesn't refresh the page and it sends to the database exactly how I want it, however, when it sends, or has an error depending on the error it should highlight the box but it doesn't. Whenever I press the button I get this error in the console:
index.php:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title></title>
<link rel="stylesheet" href="css/style.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.0/jquery.min.js"></script>
<script>
$(document).ready(function(){
$("form").submit(function(){
event.preventDefault();
var name = $("#mail-name").val();
var email = $("#mail-email").val();
var gender = $("#mail-gender").val();
var message = $("#mail-message").val();
var submit = $("#mail-sendEmail").val();
$(".form-message").load("mail.php", {
name: name,
email: email,
gender: gender,
message: message,
submit: submit
})
});
});
</script>
</head>
<body>
<form method="POST" action="mail.php">
<input type="text" name="name" id="mail-name" placeholder="Full name" value=""><br>
<input type="text" name="email" id="mail-email" placeholder="Email" value=""><br>
<select name="gender" id="mail-gender">
<option value="Male">Male</option>
<option value="Female">Female</option>
</select><br>
<textarea name="message" id="mail-message" placeholder="Message" rows="8" cols="80"></textarea><br>
<button type="submit" name="sendEmail" id="mail-sendEmail">Send email</button>
<p class="form-message"></p>
</form>
</body>
</html>
mail.php
<?php
include('inc/db.php');
if(isset($_POST['submit'])){
$name = $_POST['name'];
$email = $_POST['email'];
$gender = $_POST['gender'];
$message = $_POST['message'];
$errorEmpty = false;
$errorEmptyName = false;
$errorEmptyEmail = false;
$errorEmptyMessage = false;
$errorEmail = false;
if(empty($name) || empty($email) || empty($message)){
$errorEmpty = true;
if(empty($name)){
echo "<span class='form-error'> Please enter a name! </span><br>";
$errorEmptyName = true;
}
if(empty($email)){
echo "<span class='form-error'> Please enter an email! </span><br>";
$errorEmptyEmail = true;
}
if(empty($message)){
echo "<span class='form-error'> Please enter a message! </span><br>";
$errorEmptyMessage = true;
}
}elseif(!filter_var($email, FILTER_VALIDATE_EMAIL)){
echo "<span class='form-error'> Please enter a valid email! </span><br>";
$errorEmail = true;
}else{
echo "<span class='form-success'> Successfully sent! </span><br>";
DB::query('INSERT INTO contact VALUES(\'\', :name, :email, :gender, :message)', array(':name'=>$name, ':email'=>$email, ':gender'=>$gender, ':message'=>$message));
}
}else{
die("Error");
}
?>
<script>
$("#name, #email, #message, #gender").removeClass("input-error");
var $errorEmpty = "<?php echo "$errorEmpty" ?>";
var errorEmptyName = "<?php echo $errorEmptyName ?>";
var errorEmptyEmail = "<?php echo $errorEmptyEmail ?>";
var errorEmptyMessage = "<?php echo $errorEmptyMessage ?>";
var errorEmail = "<?php echo $errorEmail ?>";
if(errorEmpty == true){
if(errorEmptyName == true){
$("#name").addClass("input-error");
}
if(errorEmptyEmail == true){
$("#email").addClass("input-error");
}
if(errorEmptyMessage == true){
$("#message").addClass("input-error");
}
}else if(errorEmail == true){
$("#email").addClass("input-error");
}
if(errorEmpty == false && errorEmail == false){
$("#name, #email, #message").val('');
}
</script>
It doesn't call the script inside the mail.php script.

Categories