Contact Form Not Submitting - javascript

Using Zurb Foundation 5 and contact form will not submit. Nothing happens when clicking submit button. It should replace form with a thank you message and send the form data to my email. Any help greatly appreciated...
HTML:
<body>
<section id="footer">
<div class="row">
<div class="small-12 medium-6 large-6 columns">
some other stuff
</div>
<div class="small-12 medium-6 large-6 columns">
<form id="myForm" data-abide="ajax">
<div class="contactform">
<div class="name-field">
<label>Your name <small>required</small>
<input id="name" type="text" required pattern="[a-zA-Z]+">
<small class="error">Be sure and leave your name.</small>
</label>
</div>
<div class="email-field">
<label>Email <small>required</small>
<input id="email" type="email" required>
<small class="error">Oops, you forgot your email.</small>
</label>
</div>
<div class="text-field">
<label>Message <small>required</small>
</label>
<textarea id="message" required></textarea>
<small class="error">I see you're the quiet type. How about a short message?</small>
</div>
<button type="submit">Submit</button>
</div>
</form>
</div>
</div>
</section>
JS:
<script src="js/vendor/jquery.js"></script>
<script src="js/foundation.min.js"></script>
<script>
$(document).on('opened', '[data-reveal]', function () {
var modal = $(this);
$(window).trigger('resize');
});
</script>
<script>
$(document).foundation();
</script>
<script>
$('#myForm')
.on('valid.fndtn.abide', function () {
var name = $("input#name").val();
var email = $("input#email").val();
var message = $("textarea#message").val();
//Data for response
var dataString = 'name=' + name +
'&email=' + email +
'&message=' + message;
//Begin Ajax call
$.ajax({
type: "POST",
url:"php/mail.php",
data: dataString,
success: function() {
$('.contactform').html("<div id='thanks'></div>");
$('#thanks').html("<h2>Thanks!</h2>")
.append("<p>Glad to hear from you "+ name +"! I'll be in touch soon.</p>")
.hide()
.fadeIn(1500);
},
}); //ajax call
return false;
});
</script>
PHP
$name = $_POST["name"];
$email = $_POST["email"];
$message = $_POST["message"];
$msg = "
Name: $name
Email: $email
Comments:
$message
";
$to = "parker.w.gibson#gmail.com";
$subject = "Web Form";
$message = $msg;
$headers = "Web Form";
mail($to,$subject,$message,$headers);
?>
edited to separate JS

I think this is some sort of a cross domain issue.Your code is actually attempting to make a Cross-domain (CORS) request, not an ordinary POST. Modern browsers will only allow Ajax calls to services in the same domain as the request. To enable CORS on your remote server go to the following web page which gives instructions for the different types of servers .Try reading this .
FYI
CORS

Related

how to send the data of two individual contact form via mail through ajax and php?

I am working on a project. I am using HTML5 and other UI libraries.
It's a one-page layout website. I have two contact forms. first is sponsorship request form and another one for general contact/query form. I need to handle these two forms (Sponsorship form and contact us form) independently. So I am using Ajax and PHP for sending mail to my business email.
When I had only one contact form ... I tested the application on a live server. everything was working fine. Now, I added a new form, problems start rising...
I am using two js (sponsorship.js and contact_me.js) scripts and two PHP (Sponsorship.php and contact_me.php) scripts for mail, but the thing is that I am getting the response from one script when I am sending data from one contact from. but when I am trying to submit the data from both forms I get the error below in the developer console.
Failed to load sponsorship.php, Cross origin requests are only supported for protocol schemes: HTTP, data, chrome, chrome-extension, https.
failed to load contact_me.php , Cross origin requests are only supported for protocol schemes: http, data, chrome, chrome-extension, https.
below is my code
Sponsorship html code
<form name="sentMessage" id="contactForm" novalidate>
<div class="row">
<div class="col-md-6">
<div class="form-group">
<input type="text" class="form-control" placeholder="Your Full Name" style="height:60px;" id="name" required data-validation-required-message="Please enter your name.">
<p class="help-block text-danger"></p>
</div>
<div class="form-group">
<input type="email" class="form-control" placeholder="Your Valid Email" style="height:60px;" id="email" required data-validation-required-message="Please enter your email address.">
<p class="help-block text-danger"></p>
</div>
<div class="form-group">
<input type="tel" class="form-control" placeholder="Your Valid Phone Number " style="height:60px;" id="phone" required data-validation-required-message="Please enter your phone number.">
<p class="help-block text-danger"></p>
</div>
</div>
<div class="col-md-6">
<div class="form-group">
<input type="text" class="form-control" placeholder="Your Job Title" style="height:60px;" id="jobTitle" required data-validation-required-message="Please enter your Job Title.">
<p class="help-block text-danger"></p>
</div>
<div class="form-group">
<input type="text" class="form-control" placeholder="Your Company" style="height:60px;" id="company" required data-validation-required-message="Please enter your Company.">
<p class="help-block text-danger"></p>
</div>
<div class="form-group">
<select name="countries"
class="form-control" style="height:60px;" id="coutries" required>
<option value="-1">Select Country</option>
<option value="United States">United States</option>
<option value="United Kingdom">United Kingdom</option>
<option value="Afghanistan">Afghanistan</option>
</select>
<p class="help-block text-danger"></p>
</div>
</div>
<div class="clearfix"></div>
<div class="col-lg-12 text-center">
<div id="success"></div>
<br>
<button type="submit" id="Sponsorreq"
class="btn btn-primary" style="height: 50px; width:300px;">Send Message</button>
</div>
</div>
</form>
sponsorship.js
$(document).ready(function() {
$("#Sponsorreq").click(function() {
$("input,select").jqBootstrapValidation({
preventSubmit: true,
submitError: function($form, event, errors) {
// additional error messages or events
},
submitSuccess: function($form, event) {
event.preventDefault(); // prevent default submit behaviour
// get values from FORM
var name = $("input#name").val();
var email = $("input#email").val();
var phone = $("input#phone").val();
var jobTitle = $("input#jobTitle").val();
var company = $("input#company").val();
var country = $("select#country").val();
var firstName = name; // For Success/Failure Message
// Check for white space in name for Success/Fail message
if (firstName.indexOf(" ") >= 0) {
firstName = name
.split(" ")
.slice(0, -1)
.join(" ");
}
$.ajax({
url: "././mail/Sponsor.php",
type: "POST",
dataType: "jsonp",
data: {
name: name,
phone: phone,
email: email,
jobtitle: jobTitle,
company: company,
country: country
},
cache: false,
success: function() {
// Success message
$("#success").html("<div class='alert alert-success'>");
$("#success > .alert-success")
.html(
"<button type='button' class='close' data-dismiss='alert' aria-hidden='true'>×"
)
.append("</button>");
$("#success > .alert-success").append(
"<strong> Thankyou...Your Sponsor request has been sent.We will contact you shortly </strong>"
);
$("#success > .alert-success").append("</div>");
//clear all fields
$("#contactForm").trigger("reset");
},
error: function() {
// Fail message
$("#success").html("<div class='alert alert-danger'>");
$("#success > .alert-danger")
.html(
"<button type='button' class='close' data-dismiss='alert' aria-hidden='true'>×"
)
.append("</button>");
$("#success > .alert-danger").append(
"<strong>Sorry " +
firstName +
", it seems that our mail server is not responding. Please try again later!"
);
$("#success > .alert-danger").append("</div>");
//clear all fields
$("#contactForm").trigger("reset");
}
});
},
filter: function() {
return $(this).is(":visible");
}
});
$('a[data-toggle="tab"]').click(function(e) {
e.preventDefault();
$(this).tab("show");
});
});
/*When clicking on Full hide fail/success boxes */
$("#name").focus(function() {
$("#success").html("");
});
});
sponsorship.php
<?php
// Check for empty fields
if(empty($_POST['name']) ||
empty($_POST['email']) ||
empty($_POST['phone']) ||
empty($_POST['jobTitle']) ||
empty($_POST['company']) ||
empty($_POST['country']) ||
!filter_var($_POST['email'],FILTER_VALIDATE_EMAIL))
{
echo "No arguments Provided!";
return false;
}
$name = $_POST['name'];
$email_address = $_POST['email'];
$phone = $_POST['phone'];
$jobTitle = $_POST['jobTitle'];
$company = $_POST['company'];
$country = $_POST['country'];
// Create the email and send the message
$to = 'info#bangkokblockchainconference.com'; // Add your
email address inbetween the '' replacing
yourname#yourdomain.com - This is where the form will send a message to.
$email_subject = "Website Sponsor Form: $name";
$email_body = "You have received a new message from your website
Sponsor form.\n\n"."Here are the details:\n\nName:
$name\n\nEmail: $email_address\n\nPhone: $phone\n\nJob
Title:\n$jobTitle\n\nCompany:\n$company\n\nCountry:\n$country";
$headers = "From: noreply#bangkokblockchainconference.com\n"; //
This is the email address the generated message will be from.
We recommend using something like noreply#yourdomain.com.
$headers .= "Reply-To: $email_address";
mail($to,$email_subject,$email_body,$headers);
return true;
?>
contact.js and contact.php follow the same logic.
The code is not working...
Mailing is not working...
First, you have to change the forms IDs. You can't have the same ID used more than once in the same page.
And then to fix your issue. You have to update the url in your Ajax request to the current domain. The current value ././ is wrong. Instead, you can change it with ./mail/. I got it working after updating the URLs.

Novice developer - Trouble with php contact form templates - probably something dumb

I am a novice developer and for some reason I have never been able to get a php contact form to function properly. I've tried templates from bootstrapious and reusable forms but I've never been able to get them to work. My ultimate goal is to have a form with recaptcha but I can't get just a regular old form to work. Here are the codes from my latest attempt. I've been working on this for days and I feel like I'm missing something small and stupid. Thank you
<!DOCTYPE html>
<html lang="en">
<head>
<title>Contact Form Tutorial by Bootstrapious.com</title>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css" integrity="sha384-MCw98/SFnGE8fJT3GXwEOngsV7Zt27NXFoaoApmYm81iuXoPkFOJwJ8ERdknLPMO" crossorigin="anonymous">
<link href="https://fonts.googleapis.com/css?family=Lato:300,400,700" rel="stylesheet" type="text/css">
<link href="custom.css" rel="stylesheet" type="text/css">
</head>
<body>
<div class="container">
<div class="row">
<div class="col-xl-8 offset-xl-2 py-5">
<h1>Contact form Tutorial from Bootstrapious.com</h1>
<p class="lead">This is a demo for our tutorial dedicated to crafting working Bootstrap contact form with PHP and AJAX background.</p>
<p class="lead">This file uses PHPMailer to send the emails.</p>
<form id="contact-form" method="post" action="contact-2.php" role="form">
<div class="messages"></div>
<div class="controls">
<div class="row">
<div class="col-md-6">
<div class="form-group">
<label for="form_name">Firstname *</label>
<input id="form_name" type="text" name="name" class="form-control" placeholder="Please enter your firstname *" required="required" data-error="Firstname is required.">
<div class="help-block with-errors"></div>
</div>
</div>
<div class="col-md-6">
<div class="form-group">
<label for="form_lastname">Lastname *</label>
<input id="form_lastname" type="text" name="surname" class="form-control" placeholder="Please enter your lastname *" required="required" data-error="Lastname is required.">
<div class="help-block with-errors"></div>
</div>
</div>
</div>
<div class="row">
<div class="col-md-6">
<div class="form-group">
<label for="form_email">Email *</label>
<input id="form_email" type="email" name="email" class="form-control" placeholder="Please enter your email *" required="required" data-error="Valid email is required.">
<div class="help-block with-errors"></div>
</div>
</div>
<div class="col-md-6">
<div class="form-group">
<label for="form_phone">Phone</label>
<input id="form_phone" type="tel" name="phone" class="form-control" placeholder="Please enter your phone">
<div class="help-block with-errors"></div>
</div>
</div>
</div>
<div class="row">
<div class="col-md-12">
<div class="form-group">
<label for="form_message">Message *</label>
<textarea id="form_message" name="message" class="form-control" placeholder="Message for me *" rows="4" required="required" data-error="Please, leave us a message."></textarea>
<div class="help-block with-errors"></div>
</div>
</div>
<div class="col-md-12">
<input type="submit" class="btn btn-success btn-send" value="Send message">
</div>
</div>
<div class="row">
<div class="col-md-12">
<p class="text-muted"><strong>*</strong> These fields are required. Contact form template by Bootstrapious.</p>
</div>
</div>
</div>
</form>
</div><!-- /.8 -->
</div> <!-- /.row-->
</div> <!-- /.container-->
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js" integrity="sha256-FgpCb/KJQlLNfOu91ta32o/NMZxltwRo8QtmkMRdAu8=" crossorigin="anonymous"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.3/umd/popper.min.js" integrity="sha384-ZMP7rVo3mIykV+2+9J3UJ46jBk0WLaUAdn689aCwoqbBJiSnjAK/l8WvCWPIPm49" crossorigin="anonymous"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/js/bootstrap.min.js" integrity="sha384-ChfqqxuZUCnJSK3+MXmPNIyE6ZbWh2IMqE241rYiqJxyMiZ6OW/JmZQ5stwEULTy" crossorigin="anonymous"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/1000hz-bootstrap-validator/0.11.9/validator.min.js" integrity="sha256-dHf/YjH1A4tewEsKUSmNnV05DDbfGN3g7NMq86xgGh8=" crossorigin="anonymous"></script>
<script src="contact-2.js"></script>
</body>
PHP
<?php
/*
THIS FILE USES PHPMAILER INSTEAD OF THE PHP MAIL() FUNCTION
*/
require 'PHPMailer-master/PHPMailerAutoload.php';
/*
* CONFIGURE EVERYTHING HERE
*/
// an email address that will be in the From field of the email.
$fromEmail = 'uprightjared#gmail.com';
$fromName = 'Demo contact form';
// an email address that will receive the email with the output of the form
$sendToEmail = 'uprightjared#gmail.com';
$sendToName = 'Demo contact form';
// subject of the email
$subject = 'New message from contact form';
// form field names and their translations.
// array variable name => Text to appear in the email
$fields = array('name' => 'Name', 'surname' => 'Surname', 'phone' => 'Phone',
'email' => 'Email', 'message' => 'Message');
// message that will be displayed when everything is OK :)
$okMessage = 'Contact form successfully submitted. Thank you, I will get back
to you soon!';
// If something goes wrong, we will display this message.
$errorMessage = 'There was an error while submitting the form. Please try
again later';
/*
* LET'S DO THE SENDING
*/
// if you are not debugging and don't need error reporting, turn this off by
error_reporting(0);
error_reporting(E_ALL & ~E_NOTICE);
try
{
if(count($_POST) == 0) throw new \Exception('Form is empty');
$emailTextHtml = "<h1>You have a new message from your contact form</h1>
<hr>";
$emailTextHtml .= "<table>";
foreach ($_POST as $key => $value) {
// If the field exists in the $fields array, include it in the email
if (isset($fields[$key])) {
$emailTextHtml .= "<tr><th>$fields[$key]</th><td>$value</td></tr>";
}
}
$emailTextHtml .= "</table><hr>";
$emailTextHtml .= "<p>Have a nice day,<br>Best,<br>Ondrej</p>";
$mail = new PHPMailer;
$mail->setFrom($fromEmail, $fromName);
$mail->addAddress($sendToEmail, $sendToName); // you can add more addresses
by simply adding another line with $mail->addAddress();
$mail->addReplyTo($from);
$mail->isHTML(true);
$mail->Subject = $subject;
$mail->msgHTML($emailTextHtml); // this will also create a plain-text version
of the HTML email, very handy
if(!$mail->send()) {
throw new \Exception('I could not send the email.' . $mail->ErrorInfo);
}
$responseArray = array('type' => 'success', 'message' => $okMessage);
}
catch (\Exception $e)
{
// $responseArray = array('type' => 'danger', 'message' => $errorMessage);
$responseArray = array('type' => 'danger', 'message' => $e->getMessage());
}
// if requested by AJAX request return JSON response
if (!empty($_SERVER['HTTP_X_REQUESTED_WITH']) &&
strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest') {
$encoded = json_encode($responseArray);
header('Content-Type: application/json');
echo $encoded;
}
// else just display the message
else {
echo $responseArray['message'];
}
JS
$(function () {
// init the validator
// validator files are included in the download package
// otherwise download from http://1000hz.github.io/bootstrap-validator
$('#contact-form').validator();
// when the form is submitted
$('#contact-form').on('submit', function (e) {
// if the validator does not prevent form submit
if (!e.isDefaultPrevented()) {
var url = "contact-2.php";
// POST values in the background the the script URL
$.ajax({
type: "POST",
url: url,
data: $(this).serialize(),
success: function (data)
{
// data = JSON object that contact.php returns
// we recieve the type of the message: success x danger and
apply it to the
var messageAlert = 'alert-' + data.type;
var messageText = data.message;
// let's compose Bootstrap alert box HTML
var alertBox = '<div class="alert ' + messageAlert + ' alert-
dismissable"><button type="button" class="close" data-dismiss="alert" aria-
hidden="true">×</button>' + messageText + '</div>';
// If we have messageAlert and messageText
if (messageAlert && messageText) {
// inject the alert to .messages div in our form
$('#contact-form').find('.messages').html(alertBox);
// empty the form
$('#contact-form')[0].reset();
}
}
});
return false;
}
})
});

Php File For HTML Php form

I am studying on a site template for quite long. I have a contact form in my site and my html file (index.html) is linked to a js file (contact-me.js). I'm providing them below :
Contact Form In index.html :
<!-- OPEN - Content -->
<div class="item-title text-center">
<!-- Contact form -->
<form id="contact-form" name="contact-form" method="POST" data-name="Contact Form">
<div class="row">
<!-- Full name -->
<div class="col-xs-12 col-sm-6 col-lg-6">
<div class="form-group">
<input type="text" id="name" class="form form-control" placeholder="Write your name" onfocus="this.placeholder = ''" onblur="this.placeholder = 'Write your name'" name="name" data-name="Name" required>
</div>
</div>
<!-- E-mail -->
<div class="col-xs-12 col-sm-6 col-lg-6">
<div class="form-group">
<input type="email" id="email" class="form form-control" placeholder="Write your email address" onfocus="this.placeholder = ''" onblur="this.placeholder = 'Write your email address'" name="email-address" data-name="Email Address" required>
</div>
</div>
<!-- Subject -->
<div class="col-xs-12 col-sm-12 col-lg-12">
<div class="form-group">
<input type="text" id="subject" class="form form-control" placeholder="Write the subject" onfocus="this.placeholder = ''" onblur="this.placeholder = 'Write the subject'" name="subject" data-name="Subject">
</div>
</div>
<!-- Message -->
<div class="col-xs-12 col-sm-12 col-lg-12 no-padding">
<div class="form-group">
<textarea id="text-area" class="form textarea form-control" placeholder="Your message here... 20 characters Min." onfocus="this.placeholder = ''" onblur="this.placeholder = 'Your message here... 20 characters Min.'" name="message" data-name="Text Area" required></textarea>
</div>
</div>
</div>
<!-- Button submit -->
<button type="submit" id="valid-form" class="btn btn-color">Send my Message</button>
</form>
<!-- /. Contact form -->
<div id="block-answer">
<div id="answer"></div>
</div>
</div> <!-- CLOSE - Content -->
and my contact-me.js is :
$(document).ready(function() {
$("#contact-form [type='submit']").click(function(e) {
e.preventDefault();
// Get input field values of the contact form
var user_name = $('input[name=name]').val();
var user_email = $('input[name=email-address]').val();
var user_subject = $('input[name=subject]').val();
var user_message = $('textarea[name=message]').val();
// Datadata to be sent to server
post_data = {'userName':user_name, 'userEmail':user_email, 'userSubject':user_subject, 'userMessage':user_message};
// Ajax post data to server
$.post('php/contact-me.php', post_data, function(response){
// Load json data from server and output message
if(response.type == 'error') {
output = '<div class="error-message"><p>'+response.text+'</p></div>';
} else {
output = '<div class="success-message"><p>'+response.text+'</p></div>';
// After, all the fields are reseted
$('#contact-form input').val('');
$('#contact-form textarea').val('');
}
$("#answer").hide().html(output).fadeIn();
}, 'json');
});
// Reset and hide all messages on .keyup()
$("#contact-form input, #contact-form textarea").keyup(function() {
$("#answer").fadeOut();
});
});
Can You Please Help Me With The php file. I am completely new to php. Please help me with the php file that I should use for this form.
Here is a sample code.
You need a basic understanding of POST and GET method and read the PHP manual on how to use 'mail()'
<?php
$to = "mail#yourdomain.com";
$from = $_POST['user_email'];
$name = $_POST['user_name'];
$headers = "From: $from";
$subject = $_POST['user_subject'];
$body = $_POST['user_message'];
$send = mail($to, $subject, $body, $headers);
?>
I assumed that you need a php script to send you the data on your mail that user enters
I seriously have no idea why you are using Javascript(you are not verifying data,so use post action method of php. just add action="somename.php" in form tag,somewat like this
<form id="contact-form" name="contact-form" method="POST" action="somename.php">
and in somename.php keep the following content
<?php
$name = $_POST['name'];
$usermail = $_POST['email-address'];
$message = $_POST['message'];
$to = "yourmail#example.com";
$subject = $_POST['subject'];
$text = "Name-" . $name ."\nEmail-" . $usermail ."\nMessage-" . $message;
$headers = "From: webmaster#yourdomain.com" . "\r\n" .
"CC: somebodyelse#example.com";
mail($to,$subject,$text,$headers);
?>
You may continue using javascript(if so dont add action to form tag).

Form with ajax: JS not executing

I've got one big problem on only 1 page of a web site: Javascript doesn't want to be executed.
I tried to copy and paste from another web site i've done where it works perfectly... but not here. Maybe you can help me to figure out why it doesn't work...
I tried many ways, no ajax seems to work here.
Here is one of them, when i try to send a mail, i got no alert but {"reponse":"Mail sent corretly!"} instead, and the mail is corretly sent.
The submit button works! The page is refreshing, so i think the js is not executed. (i'd like to have the information without refreshing the page, like a normal ajax request).
I've tried to put the script (and the link to librairies) in the head, nothing changed.
Here is my code:
<--! Some HTML -->
<form class="form-horizontal myForm" method="post" action="contact.php">
<div class="form-group col-md-6">
<input type="text" class="form-control" name="prenom" id="prenom" placeholder="First Name" pattern="[a-zA-ZÀ-ÿ._-\s]{1,30}" required>
</div>
<div class="form-group col-md-6" style="margin-left:14px">
<input type="text" class="form-control" name="nom" id="nom" placeholder="Name" pattern="[a-zA-ZÀ-ÿ._-\s]{1,30}" required>
</div>
<div class="form-group col-md-6">
<input type="email" class="form-control" name="email" id="email" placeholder="Mail" required >
</div>
<div class="form-group col-md-6" style="margin-left:14px">
<input type="text" class="form-control" name="objet" id="objet" placeholder="Object" pattern="[a-zA-ZÀ-ÿ._-\s]{1,30}" required >
</div>
<div class="form-group col-md-12">
<input type="text" class="form-control" name="message" id="message" placeholder="Your message" required>
</div>
<div class="form-group">
<label for="captcha" class="col-xs-12 col-sm-2 control-label">Captcha</label>
<div class="col-xs-6 col-sm-2">
<input type="text" class="form-control" id="captcha" name="captcha" required>
</div>
<div class="col-xs-2 col-sm-1">
<img src="form.php">
</div>
</div>
<div class="form-group col-md-12">
<button type="submit" class="btn btn-default">Submit</button>
</div>
<div class="the-return"> </div>
</form>
<--! Some HTML -->
<script src="js/jquery-1.11.1.min.js"></script>
<script src="js/bootstrap.min.js"></script>
<script src="js/main.js"></script> <!-- Gem jQuery -->
<script>
$(document).ready(function() {
// On submit
$('.myForm').on('submit', function(e) {
e.preventDefault(); // Prevent default submit
var $this = $(this);
// Getting values
var name = $('#nom').val();
var fname = $('#prenom').val();
var objet = $('#objet').val();
var mail = $('#email').val();
var msg = $('#msg').val();
// Looking for errors
if(name === '' || fname === '' || objet === '' || mail === '' || msg === '') {
alert('Les champs doivent êtres remplis');
} else {
// Sending Ajax query
$.ajax({
url: $this.attr('action'), // form's action
type: $this.attr('method'), // form's method
data: $this.serialize(), // Serializing data
success: function(html) { // php's file response
alert(html); // Print the result
}
});
}
});
});
And my php file:
session_start();
if(isset($_GET['err']))
{
$reponse = 'Mail not sent corretly!';
echo json_encode(['reponse' => $reponse]);
echo 'An error occurred, please try again
<form .... /form>'; //Same form
}
if(isset($_POST["captcha"]) && $_POST["captcha"]!="" && $_SESSION["captcha"]==$_POST["captcha"])
{
if(isset($_POST["nom"]))
{
if(preg_match("/^[a-zA-Z][a-zA-Z]*[a-zA-Z]$/",$_POST['nom']))
{
if(isset($_POST["prenom"]))
{
if (preg_match("/^[a-zA-Z][a-zA-Z]*[a-zA-Z]$/",$_POST['prenom']))
{
if(isset($_POST["objet"]))
{
if (preg_match("/^[a-zA-Z][a-zA-Z]*[a-zA-Z]$/",$_POST['objet']))
{
if(isset($_POST["email"]))
{
if (preg_match("/^[a-zA-Z0-9._%+-]+#[a-zA-Z0-9.-]+\.[a-zA-Z]{2,4}$/",$_POST['email']))
{
$passage_ligne = "\r\n";
$emailAdmin = 'benjamin#parisbeaute.fr';
// Subject
$subject = $_POST['objet'];
// Headers
$headers = 'FROM: "'.$_POST['nom'].' '.$_POST['prenom'].'" <'.$_POST['email'].'>'.$passage_ligne;
$headers .= 'MIME-Version: 1.0'.$passage_ligne;
$headers .= 'Content-type: text/html; charset=UTF-8'.$passage_ligne;
$message = $_POST['message'];
// Formulaire
// Fonction mail()
mail($emailAdmin, $subject, $message, $headers);
echo '<div>Thanks a lot !</div>';
$reponse = 'Mail sent corretly!';
echo json_encode(['reponse' => $reponse]);
}}}}}}}}}
?>
Thanks in advance, sorry for my poor English, it's not my native language as you can see in my code.
Not sure why it did't work, but If you want sending the data using the $.ajax request, then stick to click event. Try change the code into this :
$(document).ready(function() {
// On button click
$('#my_button').on('click', function(e) {
var $this = $('.myForm');
// Getting values
var name = $('#nom').val();
var fname = $('#prenom').val();
var objet = $('#objet').val();
var mail = $('#email').val();
var msg = $('#msg').val();
// Looking for errors
if(name === '' || fname === '' || objet === '' || mail === '' || msg === '') {
alert('Les champs doivent êtres remplis');
} else {
// Sending Ajax query
$.ajax({
url: $this.attr('action'), // form's action
type: $this.attr('method'), // form's method
data: $this.serialize(), // Serializing data
success: function(html) { // php's file response
alert(html); // Print the result
}
});
}
});
});
And change button type into :
<button type="button" class="btn btn-default" id="my_button">Submit</button>

AJAX Contact Form Reloads Page but Doesn't Send Email

Hi like the title say my code seems to reload the page when hitting the send button but never actually sends the email. I've tried and read everything I could and nothing is allowing it to work properly. I would sincerely appreciate the help.
<!--[if lte IE 8]>
<script src="js/html5shiv.js"></script><![endif]-->
<script src="http://code.jquery.com/jquery-migrate-1.2.1.min.js"></script>
<script src="js/jquery.min.js"></script>
<script src="js/jquery.dropotron.js"></script>
<script src="js/skel.min.js"></script>
<script src="js/skel-panels.min.js"></script>
<script src="js/init.js"></script>
<script src="js/contact.js"></script>
<noscript>
<link rel="stylesheet" href="css/skel-noscript.css" />
<link rel="stylesheet" href="css/style.css" />
<link rel="stylesheet" href="css/style-noscript.css" />
</noscript>
<!-- Contact Form-->
<div class="content style4 featured">
<div class="container small">
<form id="contact" form method="post">
<div class="row half">
<div class="6u"><input type="text" class="text" name="name" id ="name" placeholder="Name" /></div>
<div class="6u"><input type="text" class="text" placeholder="Email" name="email" id="email"/></div>
</div>
<div class="row half">
<div class="12u"><textarea name="text" placeholder="Message" id="message"></textarea></div>
</div>
<div class="row">
<div class="12u">
<ul class="actions">
<li><input type="submit" class="button" value="Send Message" /></li>
<li><input type="reset" class="button alt" value="Clear Form" /></li>
<p class="success" style="display:none">Your message has been sent successfully.</p>
<p class="error" style="display:none">E-mail must be valid and message must be longer than 100 characters.</p>
</ul>
</div>
</div>
</form>
PHP:
<?php
// Email Submit
// Note: filter_var() requires PHP >= 5.2.0
if ( isset($_POST['email']) && isset($_POST['name']) && isset($_POST['message']) && filter_var($_POST['email'], FILTER_VALIDATE_EMAIL) ) {
// detect & prevent header injections
$test = "/(content-type|bcc:|cc:|to:)/i";
foreach ( $_POST as $key => $val ) {
if (preg_match( $test, $val ))
exit;
}
//send email
mail( "test#gmail.com", "Contact Form: ".$_POST['name'], $_POST['text'], "From:" . $_POST['email'] );
}
?>
JS:
$('#contact').submit(function(e) {
e.preventDefault();
var name = $("#name").val();
var email = $("#email").val();
var message = $("#message").val();
//var dataString = 'name=' + name + '&email=' + email + '&message=' + message;
$.ajax({
type : "POST",
url : "mail.php",
data : {name:name,email:email,message:message},
cache : false,
success : function() {
$("#contact").fadeOut(300);
$("#notice").fadeIn(400);
}
});
return false;
});
Thank you for your time.
Assuming that your email function works well in the AJAX part you need to use event.preventDefault()
Also noticed in the mail.php you have this
if ( isset($_POST['email'])
&& isset($_POST['name']) &&
**isset($_POST['text'])** &&
filter_var($_POST['email'], FILTER_VALIDATE_EMAIL) ) {
}
this will fail isset($_POST['text']) since there is no post element I suppose it should be isset($_POST['message'])
Also your form elements are missing the ids please add them as
<!-- Contact Form-->
<div class="content style4 featured">
<div class="container small">
<form id="contact" form method="post">
<div class="row half">
<div class="6u"><input type="text" class="text" name="name" id ="name" placeholder="Name" /></div>
<div class="6u"><input type="text" class="text" placeholder="Email" name="email" id="email"/></div>
</div>
<div class="row half">
<div class="12u"><textarea name="text" placeholder="Message" id="message"></textarea></div>
</div>
<div class="row">
<div class="12u">
<ul class="actions">
<li><input type="submit" class="button" value="Send Message" /></li>
<li><input type="reset" class="button alt" value="Clear Form" /></li>
<p class="success" style="display:none">Your message has been sent successfully.</p>
<p class="error" style="display:none">E-mail must be valid and message must be longer than 100 characters.</p>
</ul>
</div>
</div>
</form>
</div>
</div>
<script>
$('#contact').submit(function(e) {
e.preventDefault();
var name = $("#name").val();
var email = $("#email").val();
var message = $("#message").val();
//var dataString = 'name=' + name + '&email=' + email + '&message=' + message;
$.ajax({
type : "POST",
url : "mail.php",
data : {name:name,email:email,message:message},
cache : false,
success : function() {
$("#contact").fadeOut(300);
$("#notice").fadeIn(400);
}
});
return false;
});
</script>
I have just tested and it worked for me.
Can you modify your function, i think it is not getting called at all.
$('#contact').on('submit', function(e) {
e.preventDefault();
var name = $("#name").val();
var email = $("#email").val();
var message = $("#message").val();
//var dataString = 'name=' + name + '&email=' + email + '&message=' + message;
$.ajax({
type : "POST",
url : "mail.php",
data : {name:name,email:email,message:message},
cache : false,
success : function() {
$("#contact").fadeOut(300);
$("#notice").fadeIn(400);
}
});
return false;
});
Does your mail() function actually work by itself? Like can you send some mail using that function? Also, the PHP isset function will take mixed arguments like so...
PHP:
if(isset( $_POST['email'], $_POST['name'], $_POST['text'], filter_var($_POST['email'], FILTER_VALIDATE_EMAIL)) {
$rules = "/(content-type|bcc:|cc:|to:)/i";
foreach( $_POST as $key => value ) {
if(preg_match($rules, $value))
exit;
} //end of foreach
} //end of if
your submit button is doing a form post, u need to stop the default behavior of that button and call your method performing ajax on click of submit button.
http://api.jquery.com/event.preventdefault/
In JS you are accessing the values by id but you are giving id's just do the thing give id's for input tags i.e. name, email, message
<div class="6u"><input type="text" class="text" name="name" id="name" placeholder="Name" /></div>
<div class="6u"><input type="text" class="text" placeholder="Email" id="email" name="email" /></div>
<div
class="12u">
give your dataString as
var dataString = {name:name,email:email,message:message};
for more set header in mail i.e.
$headers = "MIME-Version: 1.0" . "\r\n";
$headers .= "Content-type:text/html;charset=iso-8859-1" . "\r\n";
$headers .= 'From: ' . "\r\n";
mail( "test#gmail.com", "Contact Form: ".$_POST['name'], $_POST['text'], "From:" .$_POST['email'] ,$headers);
better if you write it just before where the body tag is closing instead of writing in head. and above code will get executed whenever you click on an anchor tag. so be specific like this. <body> <!-- just before body tags closes--><script> $('a.buttonClassName').click(function(e){e.preventDefault(); $("<div>default"+e.type+ "prevented</div>").appendTo("#log") })</script></body>

Categories

Resources