AJAX Contact Form Reloads Page but Doesn't Send Email - javascript

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>

Related

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;
}
})
});

Ajax URL with variable form location

I'm sure the title will get my scoulded by the SO naz. . moderators. But I wasn't sure what to name it.
I have a form that I have saved in it's own php file. I include this form on the bottom of each page on the website. This is the form file.
This should be the minimum needed code to show my issue.
<?php
error_reporting(E_ALL);
//Declare variables, strip html, and php tags and then assign value from POST
if(isset($_POST['submit'])){
$name = strip_tags($_POST['name']);
$phone = strip_tags($_POST['phone']);
$email = strip_tags($_POST['email']);
$errors = array();
//Validate input
//Name
if(!empty($name)) {
//Check to see that $name only contains valid characters
if(!preg_match("/^[a-zA-Z'-]+$/", $name)) { $errors[] = "Names may only contain letters and spaces."; }
}else{
$errors[] = "Name field must be filled out.";
}
//End Name
//Phone
if(!empty($phone)) {
}else{
$errors[] = "Phone field must be filled out.";
}
//End Phone
//Email
if(!empty($email)) {
if (!filter_var($email, FILTER_VALIDATE_EMAIL)) { $errors[] = "Invalid email format."; }
}else{
$errors[] = "Email field must be filled out.";
}
//End Email
echo json_encode($errors);
}
?>
<!-- Action Form -->
<section id="sectActionForm">
<div class="row">
<div class="col1 col-md-6">
<img class="noPad" src="/images/banners/karateka.jpg">
</div>
<div id="col2" class="col-md-6 col-xs-12">
<form id="actionForm" class="" role="form" action="index.php" method="POST">
<h3>Get your FREE class today!</h3>
<input id="name" class="form-control" type="text" placeholder="Name" /><br/>
<input id="phone" class="form-control" type="text" placeholder="Phone" /><br/>
<input id="email" class="form-control" type="text" placeholder="Email" />
<input class="btn btn-lg btn-block" type="submit" value="Send" />
</form>
</div>
</div>
</section>
<script type="text/javascript">
$(document).ready(function(){
$.ajax({
type: "POST",
url: "action.include.php",
dataType: "json",
success: function(data){
alert(data);
}
})
});
</script>
<!-- END Action Form -->
My problem is that since this form could be being accessed from any page, I don't know what to put in the AJAX url section.
My DESIRED BEHAVIOR: I would like for the php errors array to be passed to the ajax so it can be displayed in a modal error box.
not sure if i'm missing something, but you would literally just put the path of the file as the url. So if the name of the form php file is myForm.php, the ajax url would be myForm.php
Try with this...
<?php
error_reporting(E_ALL);
//Declare variables, strip html, and php tags and then assign value from POST
if(isset($_POST['submit'])){
$name = strip_tags($_POST['name']);
$phone = strip_tags($_POST['phone']);
$email = strip_tags($_POST['email']);
$errors = array();
//Validate input
//Name
if(!empty($name)) {
//Check to see that $name only contains valid characters
if(!preg_match("/^[a-zA-Z'-]+$/", $name)) { $errors[] = "Names may only contain letters and spaces."; }
}else{
$errors[] = "Name field must be filled out.";
}
//End Name
//Phone
if(!empty($phone)) {
}else{
$errors[] = "Phone field must be filled out.";
}
//End Phone
//Email
if(!empty($email)) {
if (!filter_var($email, FILTER_VALIDATE_EMAIL)) { $errors[] = "Invalid email format."; }
}else{
$errors[] = "Email field must be filled out.";
}
//End Email
exit(json_encode($errors)); // exit so it doesn't send the form below
}
?>
<!-- Action Form -->
<section id="sectActionForm">
<div class="row">
<div class="col1 col-md-6">
<img class="noPad" src="/images/banners/karateka.jpg">
</div>
<div id="col2" class="col-md-6 col-xs-12">
<form id="actionForm" class="" role="form" action="index.php" method="POST">
<h3>Get your FREE class today!</h3>
<input id="name" class="form-control" type="text" placeholder="Name" /><br/>
<input id="phone" class="form-control" type="text" placeholder="Phone" /><br/>
<input id="email" class="form-control" type="text" placeholder="Email" />
<input class="btn btn-lg btn-block" type="submit" value="Send" />
</form>
</div>
</div>
</section>
<script type="text/javascript">
$("#actionForm").on('submit', function(event){
event.preventDefault(); // so it doesnt reload the page
$.ajax({
type: "POST",
url: "<?php echo $_SERVER['PHP_SELF'] ?>",
dataType: "json",
success: function(data){
alert(data);
}
});
});
</script>
<!-- END Action Form -->
Where are the 'name' attributes? All I see is 'id' and $_POST submits the name and value. Did this code ever work? What am I missing?
EDIT:
Place this line of code right above your <form>: <h4 id="errors" class="error"><?php if(isset($errors) && count($errors)) echo($errors);?></h4>. Add a class called 'error' and style it the way you want. You might want to add a <br> tag to the end of each error message. Or use the explode command instead of adding the <br> tag and the echo command.

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>

Contact Form Not Submitting

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

Ajax Contact Form Not Sending Emails [duplicate]

This question already has answers here:
Ajax Contact Form Problems - No email being sent
(2 answers)
Closed 9 years ago.
Sorry for being a noob but I'm trying my best. I've done and read everything I could find and I have never got this to work. Would really appreciate the help. The form id matches in the html and javascript. The PHP is linked in the Javascript and I have the javascript linked in the head of my html. What am I missing? I've tried other codes I found online as well and nothing.. The issue is that no email ever gets sent through. If you hit send the page reloads and thats it.
<!--[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" placeholder="Name" /></div>
<div class="6u"><input type="text" class="text" placeholder="Email" name="email" /></div>
</div>
<div class="row half">
<div class="12u"><textarea name="text" placeholder="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>
PHP:
<?php
// Email Submit
// Note: filter_var() requires PHP >= 5.2.0
if ( isset($_POST['email']) && isset($_POST['name']) && isset($_POST['text']) && 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() {
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 : dataString,
cache : false,
success : function() {
$("#contact").fadeOut(300);
$("#notice").fadeIn(400);
}
});
return false;
});
Thanks.
try preventing the default form submission by changing:
$('#contact').submit(function() {
...
to
$('#contact').submit(function(evt) {
evt.preventDefault();
//rest of your js code
and you dont have input elements with id name, email and message as per your posted code. Add those as ids to your input elements

Categories

Resources