After submitting form its showing success message on different page - javascript

After clicking the submit now button I can't get the message above the form. Please help me out in this. Please anyone.
Here is index.html form:
<form id="contact-form" method="post" action="contact.php">
<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_need">Please specify your need *</label>
<select id="form_need" name="need" class="form-control" required="required" data-error="Please specify your need.">
<option value="">-----</option>
<option value="Request quotation">Request quotation</option>
<option value="Request order status">Request order status</option>
<option value="Request copy of an invoice">Request copy of an invoice</option>
<option value="Other">Other</option>
</select>
<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">
<div class="form-group">
<div class="g-recaptcha" data-sitekey="6LdX5uQUAAAAAEPAP03K3_jafzIdoOFSblSgm2um" data-callback="verifyRecaptchaCallback" data-expired-callback="expiredRecaptchaCallback"></div>
<input class="form-control d-none" data-recaptcha="true" required data-error="Please complete the Captcha">
<div class="help-block with-errors"></div>
</div>
</div>
<div class="col-md-12">
<button type="submit" class="btn btn-success btn-send btn-danger-gradiant mt-3 mb-3 text-white border-0 py-2 px-3" value="Send message"><span> SUBMIT NOW <i class="fa fa-paper-plane"></i></span></button>
</div>
</div>
<div class="row">
<div class="col-md-12">
<p class="text-muted">
<strong>*</strong> These fields are required.
</p>
</div>
</div>
</div>
</form>
This is the contactus.js:
$(function () {
window.verifyRecaptchaCallback = function (response) {
$('input[data-recaptcha]').val(response).trigger('change');
}
window.expiredRecaptchaCallback = function () {
$('input[data-recaptcha]').val("").trigger('change');
}
$('#contact-form').validator();
$('#contact-form').on('submit', function (e) {
if (!e.isDefaultPrevented()) {
var url = "contact.php";
$.ajax({
type: "POST",
url: url,
data: $(this).serialize(),
success: function (data) {
var messageAlert = 'alert-' + data.type;
var messageText = data.message;
var alertBox = '<div class="alert ' + messageAlert + ' alert-dismissable"><button type="button" class="close" data-dismiss="alert" aria-hidden="true">×</button>' + messageText + '</div>';
if (messageAlert && messageText) {
$('#contact-form').find('.messages').html(alertBox);
$('#contact-form')[0].reset();
grecaptcha.reset();
}
}
});
return false;
}
})
});
This is the contact.php form:
<?php
// require ReCaptcha class
require('recaptcha-master/src/autoload.php');
// configure
// an email address that will be in the From field of the email.
$from = 'Demo contact form <demo#domain.com>';
// an email address that will receive the email with the output of the form
$sendTo = 'Demo contact form <demo#domain.com>';
// 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';
// ReCaptch Secret
$recaptchaSecret = '6LdX5uQUAAAAAEakfeeS4jlKkOjvSaqrawNp4gUD';
// 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 (!empty($_POST)) {
// validate the ReCaptcha, if something is wrong, we throw an Exception,
// i.e. code stops executing and goes to catch() block
if (!isset($_POST['g-recaptcha-response'])) {
throw new \Exception('ReCaptcha is not set.');
}
// do not forget to enter your secret key from https://www.google.com/recaptcha/admin
$recaptcha = new \ReCaptcha\ReCaptcha($recaptchaSecret, new \ReCaptcha\RequestMethod\CurlPost());
// we validate the ReCaptcha field together with the user's IP address
$response = $recaptcha->verify($_POST['g-recaptcha-response'], $_SERVER['REMOTE_ADDR']);
if (!$response->isSuccess()) {
throw new \Exception('ReCaptcha was not validated.');
}
// everything went well, we can compose the message, as usually
$emailText = "You have a new message from your contact form\n=============================\n";
foreach ($_POST as $key => $value) {
// If the field exists in the $fields array, include it in the email
if (isset($fields[$key])) {
$emailText .= "$fields[$key]: $value\n";
}
}
// All the neccessary headers for the email.
$headers = array('Content-Type: text/plain; charset="UTF-8";',
'From: ' . $from,
'Reply-To: ' . $from,
'Return-Path: ' . $from,
);
// Send email
mail($sendTo, $subject, $emailText, implode("\n", $headers));
$responseArray = array('type' => 'success', 'message' => $okMessage);
}
} catch (\Exception $e) {
$responseArray = array('type' => 'danger', 'message' => $e->getMessage());
}
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 {
echo $responseArray['message'];
}

Your message is on the an another page because you use action="contact.php".
Try to remove that part of code.Also remove the portion with form
<input id="form_name" type="text" name="name" class="form-control" placeholder="Please enter your firstname *" required="required" data-error="Firstname is required.">
<button type="submit" class="btn btn-success btn-send btn-danger-gradiant mt-3 mb-3 text-white border-0 py-2 px-3" onclick="addYourFunctionhere()" value="Send message"><span> SUBMIT NOW <i class="fa fa-paper-plane"></i></span></button>
<script>
function addYourFunctionhere(){
var getform_name= $("#form_name").val()
//and here use ajax to send the var from top
$.ajax({
type: "POST",
url: url,
data: {"username":getform_name},
success: function (data) {
console.log(data);
}
});
}
</script>

Related

HTML/CSS/JavaScipt and Email Configuration with PHP. Email not sending? Only prompts button as "Sending..." and then nothing happens

I am trying to send an email with PHP, but it isn't working. I think my code is correct, but I am having troubles connecting to the back-end server from my iMac computer. The form just says "Sending..." and I get no email.
What I tried:
Downloaded XAMPP and put the whole code in the htdocs folder.
Followed the prompts and installed packages to "Send Email with PHP" on the XAMPP website.
Downloaded Node.js and Express.
Tried to put file in localhost directory (not working). This is where it is located: file:///Applications/XAMPP/xamppfiles/htdocs/constructioncompany-master/public/index.html
Tried to click "Send" button and check the console.log simultaneously, and nothing happens. It's still loading with "Sending"
Checked my spam email inbox to see if it sent there.
Checked the error log in XAMPP and it says this, but not sure if this is relevant (I am new with PHP):
[Sun Jan 29 19:11:11.379312 2023] [php:error] [pid 64583] [client ::1:55351] script '/Applications/XAMPP/xamppfiles/htdocs/contact_process.php' not found or unable to stat
contact.html
<div class="row">
<div class="col-12">
<h2 class="contact-title">SEND US A MESSAGE</h2>
</div>
<div class="col-lg-8">
<form class="form-contact contact_form" action="contact_process.php" method="post" id="contactForm" novalidate="novalidate">
<div class="row">
<div class="col-sm-6">
<div class="form-group">
<input class="form-control valid" name="name" id="name" type="text" onfocus="this.placeholder = ''" onblur="this.placeholder = 'Enter your name'" placeholder="Enter your name" required="">
</div>
</div>
<div class="col-sm-6">
<div class="form-group">
<input class="form-control valid" name="email" id="email" type="email" onfocus="this.placeholder = ''" onblur="this.placeholder = 'Enter your email'" placeholder="Enter your email" required="'">
</div>
</div>
<div class="col-12">
<div class="form-group">
<input class="form-control" name="subject" id="subject" type="text" onfocus="this.placeholder = ''" onblur="this.placeholder = 'Enter subject'" placeholder="Enter subject" required="">
</div>
</div>
<div class="col-12">
<div class="form-group">
<textarea class="form-control w-100" name="message" id="message" cols="30" rows="9" onfocus="this.placeholder = ''" onblur="this.placeholder = 'Write your message'" placeholder="Write your message" required=""></textarea>
</div>
</div>
</div>
<div class="form-group mt-3">
<button type="submit" id="send" class="button boxed-btn">Send</button>
</div>
</form>
</div>
<div class="col-lg-3 offset-lg-1">
<div class="media contact-info">
<span class="contact-info__icon"><i class="ti-home"></i></span>
<div class="media-body">
<h3>San Francisco, CA, USA</h3>
</div>
</div>
<div class="media contact-info">
<span class="contact-info__icon"><i class="ti-tablet"></i></span>
<div class="media-body">
<h3>828-450-2288</h3>
</div>
</div>
<div class="media contact-info">
<span class="contact-info__icon"><i class="ti-email"></i></span>
<div class="media-body">
<h3>handtfloors#gmail.com</h3>
</div>
</div>
<div class="media contact-info">
<span class="contact-info__icon"><i class="ti-facebook"></i></span>
<div class="media-body">
<li>#SanFranciscoFloors</li>
</div>
</div>
<div class="media contact-info">
<span class="contact-info__icon"><i class="ti-instagram"></i></span>
<div class="media-body">
<li>#handtflooring</li>
</div>
</div>
</div>
PHP File
<?php
class Sendmail{
function getMailStatus(){
//Check For Submit
$status = '';
//Get Form Data
$name = htmlspecialchars($_POST['name']);
$phone = htmlspecialchars($_POST['phone']);
$email = htmlspecialchars($_POST['email']);
$title = htmlspecialchars($_POST['subject']);
$message = htmlspecialchars($_POST['message']);
if(filter_var($email, FILTER_VALIDATE_EMAIL) === false){
$status = '3';
} else {
// Passed
// Recipient Email
$toEmail = 'myemailaddress#gmail.com';
$subject = ''.$title;
$body = '<h2>H & T Flooring Contact Request</h2>
<h4>Name</h4><p>'.$name.'</p>
<h4>Phone Number</h4><p>'.$phone.'</p>
<h4>Email</h4><p>'.$email.'</p>
<h4>Message</h4><p>'.$message.'</p>
';
//Email Headers
$headers ="MIME-Version: 1.0" ."\r\n";
$headers .="Content-Type:text/html;charset=UTF-8" . "\r\n";
// Additional Headers
$headers .= "From: " .$name. "<".$email.">". "\r\n";
if(mail($toEmail, $subject, $body, $headers)){
// Email Sent
$status = '1';
} else {
//Failed
$status = '2';
}
}
return $status;
}
}
$test = new Sendmail();
echo $test->getMailStatus();
?>
contact.js
$(document).ready(function(){
$("#send").on('click', function(e){
$("#send").text('Sending...');
$("#send").attr('disabled', true);
$.ajax({
url: "/Applications/XAMPP/xamppfiles/htdocs/constructioncompany-master/public/contact_process.php",
method:"POST",
dataType:"JSON",
data:{
name:$("#name").val(),
email:$("#email").val(),
phone:$("#phone").val(),
subject:$("#subject").val(),
message:$("#message").val()
},
success:function(res){
$("#send").text('Send');
$("#send").attr('disabled', false);
if (res == 1){
$("#status").html('Message Sent Successfully! Thank you for contacting us. We will get back to you as soon as possible.');
}else if(res == 0){
$("#status").html('Message Failed.');
}else if(res == 2){
$("#status").html('Empty Fields Detected.');
}else if(res == 3){
$("#status").html('Invalid Email Address.');
}
},
error: function(err){
$('#status').html( "Network Connection Error.");
}
});
});
});
app.js
const express = require("express");
const app = express();
app.get("/", function (req, res) {
res.sendFile(__dirname + "/index.html");
});
app.listen(3000, function () {
console.log("Server is running on localhost3000");
});

Contact us form isn't sending all populated fields to email, only a few? PHP AJAX JS

So I've gone through a thread that helped me build this contact us form, but it talked about validating and making the fields required. There are two fields I have in my form that doesn't need to be required $organization and $budget, I can't seem to get the information in there to send with the email. The email shows those fields as blank but the other fields are populated.
I have practically zero experience in PHP outside of this form.
Expected output:
Name: xxx
Email: xxx#xxx.com
Organization: xxx
Budget: xxx
Message: xxx
What I actually receive in my email:
Name: xxx
Email: xxx#xxx.com
Organization:
Budget:
Message: xxx
Code:
<?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"];
}
// Organization
$organization = $_POST["organization"];
// Budget
$budget = $_POST["budget"];
// MESSAGE
if (empty($_POST["message"])) {
$errorMSG .= "Message is required ";
} else {
$message = $_POST["message"];
}
$EmailTo = "example#mydomain.com";
$Subject = "Received msg from WIP contact form";
// prepare email body text
$Body = "";
$Body .= "Name: ";
$Body .= $name;
$Body .= "\n";
$Body .= "Email: ";
$Body .= $email;
$Body .= "\n";
$Body .= "Organization: ";
$Body .= $organization;
$Body .= "\n";
$Body .= "Budget: ";
$Body .= $budget;
$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 "Sorry, something went wrong.";
} else {
echo $errorMSG;
}
}
?>
HTML:
<form role="form" id="contactForm" data-toggle="validator" class="shake">
<div class="row">
<div class="form-group col-sm-6">
<label for="name" class="h4">Name</label>
<input type="text" class="form-control" id="name" placeholder="Enter name" required>
<div class="help-block with-errors"></div>
</div>
<div class="form-group col-sm-6">
<label for="email" class="h4">Email</label>
<input type="email" class="form-control" id="email" placeholder="Enter email" required>
<div class="help-block with-errors"></div>
</div>
<div class="form-group col-sm-6">
<label for="organization" class="h4">Organization</label>
<input type="text" class="form-control" id="organization" placeholder="Enter organization">
<div class="help-block with-errors"></div>
</div>
<div class="form group col-sm-6">
<label for="budget" class="h4">Budget</label>
<input type="number" class="form-control" id="budget" placeholder="$50000">
<div class="help-block with-errors"></div>
</div>
</div>
<div class="form-group">
<label for="message" class="h4">Message</label>
<textarea id="message" class="form-control" rows="5" placeholder="Enter your message" required></textarea>
<div class="help-block with-errors"></div>
</div>
<button type="submit" id="form-submit" class="button pull-right ">Submit</button>
<div id="msgSubmit" class="h3 text-center hidden"></div>
<div class="clearfix"></div>
</form>
JavaScript:
$("#contactForm").validator().on("submit", function (event) {
if (event.isDefaultPrevented()) {
// handle the invalid form...
formError();
submitMSG(false, "Please fill in the required fields.");
} else {
// everything looks good!
event.preventDefault();
submitForm();
}
});
function submitForm(){
// Initiate Variables With Form Content
var name = $("#name").val();
var email = $("#email").val();
var message = $("#message").val();
var organization = $("#organization").val();
var budget = $("#budget").val();
$.ajax({
type: "POST",
url: "php/form-process.php",
data: "name=" + name + "&email=" + email + "&message=" + message + "&organization=" + organization + "&budget" + budget,
success : function(text){
if (text == "success"){
formSuccess();
} else {
formError();
submitMSG(false,text);
}
}
});
}
function formSuccess(){
$("#contactForm")[0].reset();
submitMSG(true, "We'll be in touch with you soon!")
}
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";
} else {
var msgClasses = "h3 text-center text-danger";
}
$("#msgSubmit").removeClass().addClass(msgClasses).text(msg);
}
EDIT
Thanks to Uxmal for suggesting the name="xxxx" in the input field. He said that by doing this, the $_POST is looking for inputs with name. Which made me realise I must be doing something else wrong. Turns out my ajax was poorly written and I was also missing the <form action aswell. Below is the corrected version of the form and ajax code.
<form action="form-process.php" method="POST" role="form" id="contactForm" data-toggle="validator" class="shake">
<div class="row">
<div class="form-group col-sm-6">
<label for="name" class="h4">Name</label>
<input type="text" class="form-control" id="name" name="name" placeholder="Enter name" required>
<div class="help-block with-errors"></div>
</div>
<div class="form-group col-sm-6">
<label for="email" class="h4">Email</label>
<input type="email" class="form-control" id="email" name="email" placeholder="Enter email" required>
<div class="help-block with-errors"></div>
</div>
</div>
<div class="row">
<div class="form-group col-sm-6">
<label for="organization" class="h4">Organization</label>
<input type="text" class="form-control" id="organization" name="organization" placeholder="Enter organization name">
<div class="help-block with-errors"></div>
</div>
<div class="form group col-sm-6">
<label for="budget" class="h4">Budget</label>
<input type="number" class="form-control" id="budget" name="budget" placeholder="50000">
<div class="help-block with-errors"></div>
</div>
</div>
<div class="form-group">
<label for="message" class="h4">Message</label>
<textarea id="message" class="form-control" rows="5" name="message" placeholder="Enter your message" required></textarea>
<div class="help-block with-errors"></div>
</div>
<button type="submit" id="form-submit" class="button pull-right ">Submit</button>
<div id="msgSubmit" class="h3 text-center hidden"></div>
<div class="clearfix"></div>
</form>
JS:
function submitForm(){
$.ajax({
type: "POST",
url: "php/form-process.php",
data: $('#contactForm').serialize(),
success: function(text) {
if (text == "success") {
formSuccess();
} else {
formError();
submitMSG(false, text);
}
}
});
}
You PHP code at line
// Organization
$organization = $_POST["organization"];
// Budget
$budget = $_POST["budget"];
looks for inputs with name: organization and budget, no to for id organization and budget.
At you html is
<input type="text" class="form-control" id="organization" placeholder="Enter organization">
<input type="number" class="form-control" id="budget" placeholder="$50000">
without a tag: name="organization" and tag: name="budget".
So put those tags like
<input type="text" class="form-control" id="organization" name="organization" placeholder="Enter organization">
<input type="number" class="form-control" id="budget" name="budget" placeholder="$50000">
and then your PHP code will get the data.

AJAX POST in same window instead of new

I tried to make a contact form within a bootstrap modal.
An alert should show up right after submitting the form in the modal.
It is working fine on my site which I use for testing.
But when I integrate the code in my main site the alert is shown as text in a new window. Same code. Different response. What could cause this behavior?
HTML:
<div class="container">
<!-- Trigger the modal with a button -->
<button type="button" class="btn btn-info btn-lg" data-toggle="modal" data-target="#myModal">Open Modal</button>
<!-- Modal -->
<div id="myModal" class="modal fade" role="dialog">
<div class="modal-dialog">
<!-- Modal content-->
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal">×</button>
<h4 class="modal-title">Modal Header</h4>
</div>
<div class="modal-body">
<form id="contact-form" method="post" action="contact.php" role="form">
<div class="messages"></div>
<div class="controls">
<div class="row">
<div class="col-md-12">
<div class="form-group">
<label for="form_name">Name</label>
<input id="form_name" type="text" name="name" class="form-control" placeholder="Please enter your firstname *" data-error="Firstname is required.">
<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_email">Email</label>
<input id="form_email" type="email" name="email" class="form-control" placeholder="Please enter your email *" data-error="Valid email is required.">
<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>
</form>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
</div>
</div>
</div>
</div>
</div>
<!-- /.container-->
PHP:
<?php
// configure
$from = 'noreplay#xy.de';
$sendTo = 'webmaster#xy.de';
$subject = 'New message from contact form';
$fields = array('name' => 'Name', 'email' => 'Email', 'message' => 'Message'); // array variable name => Text to appear in email
$okMessage = 'Contact form successfully submitted. Thank you, I will get back to you soon!';
$errorMessage = 'There was an error while submitting the form. Please try again later';
// let's do the sending
try
{
$emailText = "You have new message from contact form\n=============================\n";
foreach ($_POST as $key => $value) {
if (isset($fields[$key])) {
$emailText .= "$fields[$key]: $value\n";
}
}
mail($sendTo, $subject, $emailText, "From: " . $from);
$responseArray = array('type' => 'success', 'message' => $okMessage);
}
catch (\Exception $e)
{
$responseArray = array('type' => 'danger', 'message' => $errorMessage);
}
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 {
echo $responseArray['message'];
}
JS:
$(function () {
$('#contact-form').validator();
$('#contact-form').on('submit', function (e) {
if (!e.isDefaultPrevented()) {
var url = "contact.php";
$.ajax({
type: "POST",
url: url,
data: $(this).serialize(),
success: function (data)
{
var messageAlert = 'alert-' + data.type;
var messageText = data.message;
var alertBox = '<div class="alert ' + messageAlert + ' alert-dismissable"><button type="button" class="close" data-dismiss="alert" aria-hidden="true">×</button>' + messageText + '</div>';
if (messageAlert && messageText) {
$('#contact-form').find('.messages').html(alertBox);
$('#contact-form')[0].reset();
}
}
});
return false;
}
})
});
The action parameter in form tag action="contact.php" is forcing the page to refresh try using this as form tag :-
<form id="contact-form">
and change $(this).serialize() in your ajax post code to :-
$('#contact-form').serialize()

PHPmailer not sending mail in only Firefox

I'm having a bit of an issue with my PHPmailer service. I've tested it multiple times in Internet Explorer and Chrome. It works great. It just doesn't send anything when I try Firefox.
My domain shows it has PTR set up as well. I've checked the logs, and I've gotten no problems. Kind of at a loss for what to do.
HTML:
<div class = "myBox" ng-show="isSet(3)" ng-controller="ContactController">
<!-- Name, Company, Title, Address, City, State, County, Phone, Email, Type of request(new equipment or other pics), select one(item), comments -->
<h2 class="topProductTitle"><b>Request a Quote:</b></h2><br>
<form ng-submit="submit(contactform)" name="contactform" method="post" action="" class="form-horizontal" role="form">
<div class="form-group" ng-class="{ 'has-error': contactform.inputName.$invalid && submitted }">
<label for="inputName" class="col-lg-2 control-label">Name</label>
<div class="col-lg-10">
<input ng-model="formData.inputName" type="text" class="form-control" id="inputName" name="inputName" placeholder="Name" maxlength="25" required>
</div>
</div>
<div class="form-group" ng-class="{ 'has-error': contactform.inputCompany.$invalid && submitted }">
<label for="inputCompany" class="col-lg-2 control-label">Company</label>
<div class="col-lg-10">
<input ng-model="formData.inputCompany" type="text" class="form-control" id="inputCompany" name="inputCompany" placeholder="Company" maxlength="25" required>
</div>
</div>
<div class="form-group" ng-class="{ 'has-error': contactform.inputTitle.$invalid && submitted }">
<label for="inputTitle" class="col-lg-2 control-label">Title</label>
<div class="col-lg-10">
<input ng-model="formData.inputTitle" type="text" class="form-control" id="inputTitle" name="inputTitle" placeholder="Title" maxlength="25" required>
</div>
</div>
<div class="form-group" ng-class="{ 'has-error': contactform.inputAddress.$invalid && submitted }">
<label for="inputAddress" class="col-lg-2 control-label">Address</label>
<div class="col-lg-10">
<input ng-model="formData.inputAddress" type="text" class="form-control" id="inputAddress" name="inputAddress" placeholder="Address" maxlength="40" required>
</div>
</div>
<div class="form-group" ng-class="{ 'has-error': contactform.inputCity.$invalid && submitted }">
<label for="inputCity" class="col-lg-2 control-label">City</label>
<div class="col-lg-10">
<input ng-model="formData.inputCity" type="text" class="form-control" id="inputCity" name="inputCity" placeholder="City" maxlength="25" required>
</div>
</div>
<div class="form-group" ng-class="{ 'has-error': contactform.inputState.$invalid && submitted }">
<label for="inputState" class="col-lg-2 control-label">State</label>
<div class="col-lg-10">
<input ng-model="formData.inputState" type="text" class="form-control" id="inputState" name="inputState" placeholder="State" maxlength="25" required>
</div>
</div>
<div class="form-group" ng-class="{ 'has-error': contactform.inputPhone.$invalid && submitted }">
<label for="inputPhone" class="col-lg-2 control-label">Phone</label>
<div class="col-lg-10">
<input ng-model="formData.inputPhone" type="tel" class="form-control" id="inputPhone" name="inputPhone" placeholder="Phone" maxlength="15" required>
</div>
</div>
<div class="form-group" ng-class="{ 'has-error': contactform.inputEmail.$invalid && submitted }">
<label for="inputEmail" class="col-lg-2 control-label">Email</label>
<div class="col-lg-10">
<input ng-model="formData.inputEmail" type="email" class="form-control" id="inputEmail" name="inputEmail" placeholder="Email" maxlength="25" required>
</div>
</div>
<div class="form-group" ng-class="{ 'has-error': contactform.inputSubject.$invalid && submitted }">
<label for="inputSubject" class="col-lg-2 control-label">Subject</label>
<div class="col-lg-10">
<input ng-model="formData.inputSubject" type="text" class="form-control" id="inputSubject" name="inputSubject" placeholder="Subject Message" maxlength="25" required>
</div>
</div>
<div class="form-group" ng-class="{ 'has-error': contactform.inputMessage.$invalid && submitted }">
<label for="inputMessage" class="col-lg-2 control-label">Message</label>
<div class="col-lg-10">
<textarea ng-model="formData.inputMessage" class="form-control" rows="4" id="inputMessage" name="inputMessage" placeholder="Your message..." required></textarea>
</div>
</div>
<div class="form-group">
<div class="col-lg-offset-2 col-lg-10">
<button type="submit" class="btn btn-primary btn-md" ng-disabled="submitButtonDisabled">
<h4>Send Message</h4>
</button>
</div>
</div>
</form>
</div>
Angular:
app.controller('ContactController', function ($scope, $http) {
$scope.result = 'hidden'
$scope.resultMessage;
$scope.formData; //formData is an object holding the data.
$scope.submitButtonDisabled = false;
$scope.submitted = false; //used so that form errors are shown only after the form has been submitted
$scope.submit = function(contactform)
{
$scope.submitted = true;
$scope.submitButtonDisabled = true;
if (contactform.$valid) {
$http({
method : 'POST',
url : 'contact-form.php',
data : $.param($scope.formData), //param method from jQuery
headers : { 'Content-Type': 'application/x-www-form-urlencoded' } //set the headers so angular passing info as form data (not request payload)
}).success(function(data){
console.log(data);
if (data.success) { //success comes from the return json object
$scope.submitButtonDisabled = true;
$scope.resultMessage = data.message;
$scope.result='bg-success';
} else {
$scope.submitButtonDisabled = false;
$scope.resultMessage = data.message;
$scope.result='bg-danger';
}
});
} else {
$scope.submitButtonDisabled = false;
$scope.resultMessage = 'Failed! Please fill out all the fields.';
$scope.result='bg-danger';
}
}
});
PHP:
<?php
require_once 'PHPMailer-master/PHPMailerAutoload.php';
if (isset($_POST['inputName']) && isset($_POST['inputEmail']) && isset($_POST['inputSubject']) && isset($_POST['inputMessage'])) {
//check if any of the inputs are empty
if (empty($_POST['inputName']) || empty($_POST['inputEmail']) || empty($_POST['inputSubject']) || empty($_POST['inputMessage'])) {
$data = array('success' => false, 'message' => 'Please fill out the form completely.');
echo json_encode($data);
exit;
}
//create an instance of PHPMailer
$mail = new PHPMailer();
$mail->From = $_POST['inputEmail'];
$mail->FromName = $_POST['inputName'];
$mail->AddAddress('test2#gmail.com'); //recipient
$mail->Subject = $_POST['inputSubject'];
$mail->Body = "Name: " . $_POST['inputName'] . "\r\n\r\nCompany: " . stripslashes($_POST['inputCompany']) ."\r\n\r\nTitle: " . stripslashes($_POST['inputTitle']) . "\r\n\r\nAddress: " . stripslashes($_POST['inputAddress'])
. "\r\n\r\nCity: " . stripslashes($_POST['inputCity']) . "\r\n\r\nState: " . stripslashes($_POST['inputState']) . "\r\n\r\nPhone: " . stripslashes($_POST['inputPhone']) . "\r\n\r\nEmail: " . stripslashes($_POST['inputEmail'])
. "\r\n\r\nMessage: " . stripslashes($_POST['inputMessage']);
$mail->isSMTP();
$mail->Host = gethostbyname('smtp.gmail.com');
$mail->Port = 587;
$mail->SMTPDebug = 1;
$mail->SMTPSecure = "tls";
$mail->SMTPAuth = true;
$mail->Username = "Test#gmail.com";
$mail->Password = "123";
$mail->setFrom('Test#gmail.com', 'Contact Form');
if (isset($_POST['ref'])) {
$mail->Body .= "\r\n\r\nRef: " . $_POST['ref'];
}
if(!$mail->send()) {
$data = array('success' => false, 'message' => 'Message could not be sent. Mailer Error: ' . $mail->ErrorInfo);
echo json_encode($data);
exit();
}
$data = array('success' => true, 'message' => 'Thanks! We have received your message.');
echo json_encode($data);
} else {
$data = array('success' => false, 'message' => 'Please fill out the form completely.');
echo json_encode($data);
}
I have exactly the same thing. My mailer works with Chrome and Edge, but not Firefox. This cut-down code, called from the address bar, behaves the same:
$subject="FIREFOX test";
$scrnmess = "Howdee doodee";
$email="canthaveit.com";
$recipient="webmaster#waterfowl.org.uk";
$headers = "MIME-Version: 1.0" . "\r\n";
$headers .= "Content-type:text/html;charset=UTF-8" . "\r\n";
$headers .= "From: " . $email . "\r\n";
mail($recipient, $subject, $scrnmess, $headers);

Ajax not posting form data

I recently asked a question about executing a Send Mail script without a page reload and worked out what my problem was with my AJAX, that's all resolved. I now have an issue with the following:
When my form posts to my AJAX the script is executed, however the post data doesn't seem to be come through to the PHP script.
The link to my question is: Contact Form same page success.
Here is my PHP:
<?php
$name = ($_POST['name']);
$email = ($_POST['email']);
$fsubject = ($_POST['subject']);
$message = ("Name: ". $name . "\nEmail Address: " . $email . "\n\nMessage: " . $_POST['message']);
// Set Mail
$to = "emailaddress#fakeone.com";
$header = 'From: contactus#fakeone.com' . "\r\n" .
'Reply-To: website#fakeone.com';
$subject = "{$fsubject}";
$body = "{$message}";
// Send Mail
if (mail($to, $subject, $body, $header))
{
echo("<p>Message successfully sent!</p>");
}
else
{
echo("<p>Message delivery failed...</p>");
}
?>
My HTML
<div id="success" style="color:red;"></div>
<form action="" id="contactform" method="post">
<div class="row">
<div class="form-group">
<div class="col-md-6">
<label>Your name *</label>
<input type="text" value="" data-msg-required="Please enter your name." maxlength="100" class="form-control" name="name" id="name">
</div>
<div class="col-md-6">
<label>Your email address *</label>
<input type="email" value="" data-msg-required="Please enter your email address." data-msg-email="Please enter a valid email address." maxlength="100" class="form-control" name="email" id="email">
</div>
</div>
</div>
<div class="row">
<div class="form-group">
<div class="col-md-12">
<label>Subject</label>
<input type="text" value="" data-msg-required="Please enter the subject." maxlength="100" class="form-control" name="subject" id="subject">
</div>
</div>
</div>
<div class="row">
<div class="form-group">
<div class="col-md-12">
<label>Message *</label>
<textarea maxlength="5000" data-msg-required="Please enter your message." rows="10" class="form-control" name="message" id="message"></textarea>
</div>
</div>
</div>
<div class="row">
<div class="col-md-12">
<input type="submit" id="submit" value="Send Message" class="btn btn-info btn-lg" data-loading-text="Loading...">
</div>
</form>
My AJAX
<script>
$(document).ready(function () {
$('#submit').click(function () {
$.post("sendmail.php", $("#contactform").serialize(), function (response) {
$('#success').html(response);
});
return false;
});
});
</script>
When I fill out the forms, nothing comes back it sends an empty email.
Any idea's why the post isn't working on this would be greatly appreciated. If I am breaking any rules by posting another question please let me know!
Regards,
Dan
I think the problem is in your PHP code. You've got a variable named $headers, but in your mail function you're using $header. A typo.
Change the following lines from this -
$subject = "{$fsubject}";
$body = "{$message}";
to this -
$subject = $fsubject;
$body = $message;

Categories

Resources