PHP mail function has stopped working - email

I have created a contact form that sends an email to the website administrator and to the person who filled out the contact form. It was working fine and I have just come back to it to do some more testing and it has stopped sending. To my knowledge I've not changed any of the code. I can't figure out what is wrong with it. Can someone help? Below is the code for the three files I'm using.
This is the contact form file:
<div id="contact-form" class="contact-form">
<div class="rounded-box">
<div class="rounded-box-title">
<h3>Ask for a call back</h3>
<img src="<?php echo get_bloginfo('url') ?>/images-default/br_next.png"/>
</div><!-- .rounded-box-title -->
<?php
$cf = array();
if(isset($_SESSION['cf_returndata'])){
$cf = $_SESSION['cf_returndata'];
?>
<div id="success" class="success"><?php echo ($cf['success']); ?></div>
<script>
$("#success").delay(6000).slideUp();
</script>
<?php
}
?>
<div class="required-text-line">
<span class="required">*</span><span class="required-text">indicates required field</span>
</div>
<form name="contact-form" onsubmit="return validateForm()" action="<?php bloginfo('url'); ?>/wp-content/themes/example/contact-form-send.php" method="POST">
<fieldset>
<label for="fname"><span class="required">*</span>First name:</label></br>
<input type="text" name="fname" id="fname" onblur="return validateFirstName()" value="" />
<span class="error" id="fnameError" style="display: none;"></span>
<script>
$("#fname").blur(function(){
$("#fnameError").delay(6000).slideUp();
})
</script>
</fieldset>
<fieldset>
<label for="lname"><span class="required">*</span>Last name:</label></br>
<input type="text" name="lname" id="lname" onblur="return validateLastName()" value="" />
<span class="error" id="lnameError" style="display: none;"></span>
<script>
$("#lname").blur(function(){
$("#lnameError").delay(6000).slideUp();
})
</script>
</fieldset>
<fieldset>
<label for="email"><span class="required">*</span>Email:</label></br>
<input type="text" name="email" id="email" onblur="return validateEmail()" value="" />
<span class="error" id="emailError" style="display: none;"></span>
<script>
$("#email").blur(function(){
$("#emailError").delay(6000).slideUp();
})
</script>
</fieldset>
<fieldset>
<label for="tel"><span class="required">*</span>Telephone:</label></br>
<input type="text" name="tel" id="tel" onblur="return validateTel()" value="" />
<span class="error" id="telError" style="display: none;"></span>
<script>
$("#tel").blur(function(){
$("#telError").delay(6000).slideUp();
})
</script>
</fieldset>
<fieldset>
<label for="message"><span class="required">*</span>Message:</label></br>
<textarea name="message" id="message" onblur="return validateMessage()" ></textarea>
<span class="error" id="messageError" style="display: none;"></span>
<script>
$("#message").blur(function(){
$("#messageError").delay(6000).slideUp();
})
</script>
</fieldset>
<fieldset id="hiddenfield">
<label for="hidden"></label>
<textarea name="hidden" id="hidden" ></textarea>
</fieldset>
<input type="submit" value="Submit" id="submit" />
<script>
$("form").submit(function(){
$(".error").delay(6000).slideUp();
})
</script>
</form>
<?php unset($_SESSION['cf_returndata']); ?>
</div><!-- .rounded-box -->
</div><!-- .contact-form -->
This is the send PHP file:
<?php
if( isset($_POST) ){
if (empty($_POST ['hidden'])) {
$fname = htmlspecialchars($_POST ['fname']);
$lname = htmlspecialchars($_POST ['lname']);
$email = htmlspecialchars($_POST ['email']);
$tel = htmlspecialchars($_POST ['tel']);
$message = htmlspecialchars($_POST ['message']);
$to = "example#gmail.com";
$subject = "Callback request";
$body = "
<html>
<head>
</head>
<header style='padding:10px'>
<a href='http://example.com'>
<img src='http://example.com/images-default/example-logo.png' alt='example.com'>
</a>
</header>
<body style='border-top:2px solid #91448D;margin-top:15px'>
<p>You have recieved an message through the callback request form on the website.</p>
<p><strong>Name: </strong>{$fname} {$lname} </p>
<p><strong>Email: </strong>{$email} </p>
<p><strong>Telephone: </strong>{$tel} </p>
<p><strong>Message: </strong>{$message}</p>
</body>
</html>
";
$headers = 'MIME-Version: 1.0' . "\r\n";
$headers .= 'Content-type: text/html; charset=iso-8859-1' . "\r\n";
$headers .= 'From: example <info#example.com>' . "\r\n";
$headers .= 'Reply-To: info#example.com' . "\r\n";
mail ( //email to info#example.com
$to,
$subject,
$body,
$headers
);
$subject2 = "Thanks for your enqiry";
$body2 = "
<html>
<head>
</head>
<header style='padding:10px'>
<a href='http://example.com'>
<img src='http://example.com/images-default/example-logo.png' alt='example.com'>
</a>
</header>
<body style='border-top:2px solid #91448D;margin-top:15px'><br/>
<p style='margin-bottom:1em'>Hi {$fname},<br/><br/>
Thanks for enquiring about private maths tuition with <a href='http://example.com'>example.com</a>.<br/><br/>
We'll get back to you within 24 hours for a chat about your child's learning needs.<br/><br/>
Regards,<br/><br/>
<strong>Kathy</strong><br/>
<a href='http://example.com'>example.com</a> founder<br/>
tel: 01582 472060<br/>
email: <a href='mailto:info#example.com'>info#example.com</a></p>
</body>
</html>
";
mail ( //email to enquiror
$email,
$subject2,
$body2,
$headers
);
$success = "Thank you for your enquiry. We'll get back to you within 24 hours.";
$returndata = array (
'success' => $success
);
session_start();
$_SESSION['cf_returndata'] = $returndata;
header('location: ' . $_SERVER['HTTP_REFERER']);
}
}
?>
This is the javascript validation file:
function validateFirstName(){
if (
document.getElementById('fname').value == "") {
document.getElementById('fnameError').style.display = "block";
document.getElementById('fnameError').innerHTML = "Please enter your first name";
return false;
}
else {
document.getElementById('fnameError').style.display = "none";
return true;
}
}
function validateLastName(){
if (
document.getElementById('lname').value == "") {
document.getElementById('lnameError').style.display = "block";
document.getElementById('lnameError').innerHTML = "Please enter your last name";
return false;
}
else {
document.getElementById('lnameError').style.display = "none";
return true;
}
}
function validateEmail(){
var re = /^(([^<>()[\]\\.,;:\s#\"]+(\.[^<>()[\]\\.,;:\s#\"]+)*)|(\".+\"))#((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
if (
re.test(document.getElementById('email').value)){
document.getElementById('emailError').style.display = "none";
return true;
}
else {
if (
document.getElementById('email').value == "") {
document.getElementById('emailError').style.display = "block";
document.getElementById('emailError').innerHTML = "Please enter your email address";
return false;
}
else {
document.getElementById('emailError').style.display = "block";
document.getElementById('emailError').innerHTML = "Please enter a valid email address";
return false;
}
}
}
function validateTel(){
var re = /(((\+44)? ?(\(0\))? ?)|(0))( ?[0-9]{3,4}){3}/;
if (
re.test(document.getElementById('tel').value)){
document.getElementById('telError').style.display = "none";
return true;
}
else {
if (
document.getElementById('tel').value == "") {
document.getElementById('telError').style.display = "block";
document.getElementById('telError').innerHTML = "Please enter your phone number";
return false;
}
else {
document.getElementById('telError').style.display = "block";
document.getElementById('telError').innerHTML = "Please enter a valid phone number";
return false;
}
}
}
function validateMessage(){
if (
document.getElementById('message').value == "") {
document.getElementById('messageError').style.display = "block";
document.getElementById('messageError').innerHTML = "Please enter a message";
return false;
}
else {
document.getElementById('messageError').style.display = "none";
return true;
}
}
function validateForm(){
// Set error catcher
var error = 0;
// Check first name
if(!validateFirstName(document.getElementById('fname').value)){
document.getElementById('fnameError').style.display = "block";
error++;
}
// Check last name
if(!validateLastName(document.getElementById('lname').value)){
document.getElementById('lnameError').style.display = "block";
error++;
}
// Validate email
if(!validateEmail(document.getElementById('email').value)){
document.getElementById('emailError').style.display = "block";
error++;
}
// Validate phone number
if(!validateTel(document.getElementById('tel').value)){
document.getElementById('telError').style.display = "block";
error++;
}
if(!validateMessage(document.getElementById('message').value)){
document.getElementById('messageError').style.display = "block";
error++;
}
if (
!document.getElementById('hidden').value == "") {
error++;
}
if(error > 0){
return false;
}
}

Related

Sending a form via PHPMailer to an EMail adress - not working

I am trying to implement a form on my website - and make a PHPMailer send the content to my email address. I followed the directions from this website: https://www.codingsnow.com/2021/01/create-php-send-email-contact-form.html
But its not working. I tried different email addresses, I tried tls and other ports and many more - nothing. Its alway the same: When I click the submit button, nothing happens. There's neither a success nor a failed echo.
I could really need some help!
This is the form code:
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Contact</title>
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css" integrity="sha384-Vkoo8x4CGsO3+Hhxv8T/Q5PaXtkKtu6ug5TOeNV6gBiFeWPGFN9MuhOf23Q9Ifjh" crossorigin="anonymous">
<style type="text/css">
input, textarea {
margin-top: 10px;
}
</style>
</head>
<body>
<div class="container" style="margin-top:100px;">
<div class="row justify-content-center">
<div class="col-md-6 col-md-offset-3" align="center">
<input id="name" placeholder="Name" class="form-control">
<input id="email" placeholder="Email" class="form-control">
<input id="subject" placeholder="Subject" class="form-control">
<textarea class="form-control" id="body" placeholder="Email Body"></textarea>
<input type="button" onclick="sendEmail()" value="Send an Email" class="btn btn-primary"></type>
</div>
</div>
</div>
<script type="text/javascript">
function sendEmail() {
console.log('sending...');
var name = $("#name");
var email = $("#email");
var subject = $("#subject");
var body = $("#body");
if (isNotEmpty(name) && isNotEmpty(email) && isNotEmpty(subject) && isNotEmpty(body)) {
$.ajax({
url: 'sendEmail.php',
method: 'POST',
dataType: 'json',
data: {
name: name.val(),
email: email.val(),
body: body.val()
}, success: function (response) {
console.log(response)
}
});
}
}
function isNotEmpty(caller) {
if (caller.val() === "") {
caller.css('border', '1px solid red');
return false;
} else {
caller.css('border', '');
}
return true;
}
</script>
</body>
</html>
And this is the sendEmail.php:
<?php
use PHPMailer\PHPMailer\PHPMailer;
if(isset($_POST['name']) && isset($_POST['email'])){
$name = $_POST['name'];
$email = $_POST['email'];
$subject = $_POST['subject'];
$body = $_POST['body'];
require_once "PHPMailer/PHPMailer.php";
require_once "PHPMailer/SMTP.php";
require_once "PHPMailer/Exception.php";
$mail = new PHPMailer();
//smtp settings
$mail->SMTPDebug = 2;
$mail->isSMTP();
$mail->Host = "smtp.gmail.com";
$mail->SMTPAuth = true;
$mail->Username = "mymail#gmail.com";
$mail->Password = 'mypassword';
$mail->Port = 465;
$mail->SMTPSecure = "ssl";
//email settings
$mail->isHTML(true);
$mail->setFrom($email, $name);
$mail->addAddress("mymail#gmail.com");
$mail->Subject = ("$email ($subject)");
$mail->Body = $body;
if($mail->send()){
$status = "success";
$response = "Email is sent!";
}
else
{
$status = "failed";
$response = "Something is wrong: <br>" . $mail->ErrorInfo;
}
exit(json_encode(array("status" => $status, "response" => $response)));
}
if ($mail->send()) {
$status = "success";
echo "Email is sent!";
} else {
$status = "failed";
echo "Something is wrong: <br><br>" . $mail->ErrorInfo;
}
?>
Thank you for your time and knowledge!
Andre
P.S.: #Merchizm: Thanks, I have changed the code, now it looks like this:
<?php
require_once "PHPMailer/PHPMailer.php";
require_once "PHPMailer/SMTP.php";
require_once "PHPMailer/Exception.php";
use PHPMailer\PHPMailer\PHPMailer;
if(isset.... and so on
Is this, what you mean?
I also added the jQuery to the head of the html file like this:
<script src="jquery-3.3.1.min.js" type="text/javascript"></script>
<script type="text/javascript" src="jquery30102019.js"></script>
But nevertheless, it is not working. Still the same issue.
Do you have another idea?
Thanks Andre
The JQuery library is not included in the html file, the request may not be going because of this.
Require files before using class.
require_once __DIR__. "/PHPMailer/src/PHPMailer.php";
require_once __DIR__."/PHPMailer/src/SMTP.php";
require_once __DIR__."/PHPMailer/src/Exception.php";
use PHPMailer\PHPMailer\PHPMailer;
I think these will solve your problem.

How to add a 'Send Message To' button on contact page?

I'm trying to add a "Send Message To" button on a contact form but I'm having trouble with the javascript/PHP. I'm using code I edited that came with the start bootstrap modern business theme, so far I have just added the $to = '$department', set the select tag ID as department and the value of option tags to the appropriate emails.
Not sure if any of that is correct.
HTML:
<div class="row">
<div class="col-lg-8 mb-4">
<h3>Send us a Message</h3>
<form name="sentMessage" id="contactForm" novalidate>
<div class="control-group form-group">
<div class="controls">
<label>Full Name</label>
<input type="text" class="form-control" id="name" required data-validation-required-message="Please enter your name.">
<p class="help-block"></p>
</div>
</div>
<div class="control-group form-group">
<div class="controls">
<label>Email Address</label>
<input type="email" class="form-control" id="email" required data-validation-required-message="Please enter your email address.">
</div>
</div>
<div class="control-group form-group">
<div class="controls">
<label>Message</label>
<textarea rows="10" cols="100" class="form-control" id="message" required data-validation-required-message="Please enter your message" maxlength="999" style="resize:none"></textarea>
</div>
</div>
<div class="control-group form-group">
<div class="controls">
<label>Send Message To</label>
<select class="form-control" id="department">
<option value="sales#website.com">Sales</option>
<option value="support#website.com">Support</option>
</select>
<p class="help-block"></p>
</div>
</div>
<div id="success"></div>
<!-- For success/fail messages -->
<button type="submit" class="btn btn-CMD" id="sendMessageButton">Send Message</button>
</form>
</div>
</div>
PHP:
<?php
// Check for empty fields
if(empty($_POST['name']) ||
empty($_POST['email']) ||
empty($_POST['message']) ||
!filter_var($_POST['email'],FILTER_VALIDATE_EMAIL))
{
echo "No arguments Provided!";
return false;
}
$name = strip_tags(htmlspecialchars($_POST['name']));
$email_address = strip_tags(htmlspecialchars($_POST['email']));
$message = strip_tags(htmlspecialchars($_POST['message']));
$message = strip_tags(htmlspecialchars($_POST['department']));
// Create the email and send the message
$to = '$department';
$email_subject = "Website Contact Form: $name";
$email_body = "You have received a new message from your website contact form.\n\n"."Here are the details:\n\nName: $name\n\nEmail: $email_address\n\nMessage:\n$message";
$headers = "From: noreply#website.com\n";
$headers .= "Reply-To: $email_address";
mail($to,$email_subject,$email_body,$headers);
return true;
?>
Javascript
$(function() {
$("#contactForm input,#contactForm textarea").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 message = $("textarea#message").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(' ');
}
$this = $("#sendMessageButton");
$this.prop("disabled", true); // Disable submit button until AJAX call is complete to prevent duplicate messages
$.ajax({
url: "././mail/contact_me.php",
type: "POST",
data: {
name: name,
email: email,
message: message
},
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>Your message has been sent. </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>").text("Sorry " + firstName + ", it seems that my mail server is not responding. Please try again later!"));
$('#success > .alert-danger').append('</div>');
//clear all fields
$('#contactForm').trigger("reset");
},
complete: function() {
setTimeout(function() {
$this.prop("disabled", false); // Re-enable submit button when AJAX call is complete
}, 1000);
}
});
},
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('');
});
Im not quite sure about your questions, but if you're just trying to get the item from the department form, and send it to that email address, this is the code for that.
JS:
data: {
name: name,
email: email,
message: message,
department: document.getElementById('department').value
},
You must pass the value of the form to the PHP script. You originally had the $message var set to the message and then the next line would set that variable to the department. You need to keep them separate.
$name = strip_tags(htmlspecialchars($_POST['name']));
$email_address = strip_tags(htmlspecialchars($_POST['email']));
$message = strip_tags(htmlspecialchars($_POST['message']));
$department = strip_tags(htmlspecialchars($_POST['department']));
// Create the email and send the message
$to = $department;
$email_subject = "Website Contact Form: $name";
$email_body = "You have received a new message from your website contact form.\n\n"."Here are the details:\n\nName: $name\n\nEmail: $email_address\n\nMessage:\n$message";
$headers = "From: noreply#website.com\n";
$headers .= "Reply-To: $email_address";
mail($to,$email_subject,$email_body,$headers);
return true;
?>
Hope this works!

PHPMailer and Ionic with Gmail

I'm attempting to create a contact form for my app using PHPMailer and Ionic with Gmail.
The page receives (Failed.) result message when it triggers the script but I never get the email from the form. Here is my code:
template.html
<label class="item item-input" ng-class="{ 'has-error': contactform.inputEmail.$invalid && submitted }">
<input ng-model="formData.inputEmail" type="email" class="form-control" id="inputEmail" name="inputEmail" placeholder="Your Email" required>
</label>
<label class="item item-input" ng-class="{ 'has-error': contactform.inputSubject.$invalid && submitted }">
<input ng-model="formData.inputSubject" type="text" class="form-control" id="inputSubject" name="inputSubject" placeholder="Subject Message" required>
</label>
<label class="item item-input" ng-class="{ 'has-error': contactform.inputMessage.$invalid && submitted }">
<textarea ng-model="formData.inputMessage" class="form-control" rows="4" id="inputMessage" name="inputMessage" placeholder="Your message..." required></textarea>
</label>
<div class="padding">
<button type="submit" class="btn btn-default" ng-disabled="submitButtonDisabled">Send Message</button>
</div>
</form>
<p ng-class="result" style="padding: 15px; margin: 0;">{{ resultMessage }}</p>
app.js
.controller('ContactCtrl', function ($scope, $http) {
$scope.result = 'hidden'
$scope.resultMessage;
$scope.formData; //formData is an object holding the name, email, subject, and message
$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.';
$scope.result='bg-danger';
}
}
});
PHP
<?php
require_once 'phpmailer/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('my#emailaddress.com'); //recipient
$mail->Subject = $_POST['inputSubject'];
$mail->Body = "Name: " . $_POST['inputName'] . "\r\n\r\nMessage: " . stripslashes($_POST['inputMessage']);
$mail->isSMTP();
$mail->Host = gethostbyname('smtp.gmail.com');
$mail->Port = 587;
$mail->SMTPSecure = "tls";
$mail->SMTPAuth = true;
$mail->Username = "mygmailusername#gmail.com";
$mail->Password = "passwordform";
$mail->setFrom('mygmailusername#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);
}
You need to initialize $scope.formData = {} so that it can hold the values you are expecting. Right now, its trying to bind values to a scope variable that is undefined.
Edit - It looks like you have no ng-click handler in your button to register the click to the submit. Please add this to your button. Additionally, $valid only works if your input values are enclosed in a .
template.html
<form name="myForm">
<label class="item item-input" ng-class="{ 'has-error': contactform.inputEmail.$invalid && submitted }">
<input ng-model="formData.inputEmail" type="email" class="form-control" id="inputEmail" name="inputEmail" placeholder="Your Email" required>
</label>
<label class="item item-input" ng-class="{ 'has-error': contactform.inputSubject.$invalid && submitted }">
<input ng-model="formData.inputSubject" type="text" class="form-control" id="inputSubject" name="inputSubject" placeholder="Subject Message" required>
</label>
<label class="item item-input" ng-class="{ 'has-error': contactform.inputMessage.$invalid && submitted }">
<textarea ng-model="formData.inputMessage" class="form-control" rows="4" id="inputMessage" name="inputMessage" placeholder="Your message..." required></textarea>
</label>
<div class="padding">
<button type="submit" class="btn btn-default"
ng-disabled="myForm.$invalid || submitButtonDisabled == true"
ng-click=submit(formData)>Send Message</button>
</div>
</form>
<p ng-class="result" style="padding: 15px; margin: 0;">{{ resultMessage }}</p>
What this is doing is its registering the $scope.submit the button, and in the HTML you're passing in formData as a parameter. The now has a name and its required values are checked in ng-disabled of the button which refers to the same name and disables if the I've cleaned up your app.js so that you're getting the params correctly.
.controller('ContactCtrl', function ($scope, $http) {
$scope.result = 'hidden'
$scope.resultMessage = '';
$scope.formData; //formData is an object holding the name, email, subject, and message
$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;
$http({
method : 'POST',
url : 'contact-form.php',
data : $.param(contactform), //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';
}
});
}
});

Login change in to signup

I have created a HTML5 registration form,is it possible for it to check the email address(inserted first) if it's already used to ask only for password(login) and if it's not to insert other fields needed for signup? using php,js or others.
<form id="signin_student" class="form-signin" method="post">
<h3 class="form-signin-heading"><i class="icon-lock"></i> Register </h3>
<input type="text" class="input-block-level" id="username" name="username" placeholder="NISN" required>
<input type="text" class="input-block-level" id="firstname" name="firstname" placeholder="Nama Depan" required>
<input type="text" class="input-block-level" id="lastname" name="lastname" placeholder="Nama Belakang" required>
<label>Kelas</label>
<select name="class_id" class="input-block-level span5">
<option>Pilih Kelas</option>
<?php
$query = mysql_query("select * from class order by class_name ")or die(mysql_error());
while($row = mysql_fetch_array($query)){
?>
<option value="<?php echo $row['class_id']; ?>"><?php echo $row['class_name']; ?></option>
<?php
}
?>
</select>
<input type="password" class="input-block-level" id="password" name="password" placeholder="Password" required>
<input type="password" class="input-block-level" id="cpassword" name="cpassword" placeholder="Tulis Ulang Password" required>
<button title="Klik untuk Daftar" id="signin" name="login" class="btn btn-info" type="submit"><i class="icon-check icon-large"></i> Daftar</button>
</form>
<script>
jQuery(document).ready(function(){
jQuery("#signin_student").submit(function(e){
e.preventDefault();
var password = jQuery('#password').val();
var cpassword = jQuery('#cpassword').val();
if (password == cpassword){
var formData = jQuery(this).serialize();
$.ajax({
type: "POST",
url: "student_signup.php",
data: formData,
success: function(html){
if(html=='true')
{
var delay = 2000;
setTimeout(function(){ window.location = 'siswa/index.php' }, delay);
}else if(html=='false'){
{ header: 'Data in DB is Not Found' });
}
}
});
}else
{
$.jGrowl("student does not found in the database", { header: 'Sign Up Failed' });
}
});
});
</script>
and file signup.php
<?php
mysql_select_db('db',mysql_connect('localhost','root',''))or die(mysql_error());
session_start();
$username = $_POST['username'];
$password = $_POST['password'];
$firstname = $_POST['firstname'];
$lastname = $_POST['lastname'];
$class_id = $_POST['class_id'];
$query = mysql_query("select * from student where username='$username' and firstname='$firstname' and lastname='$lastname' and class_id = '$class_id'")or die(mysql_error());
$row = mysql_fetch_array($query);
$id = $row['student_id'];
$count = mysql_num_rows($query);
if ($count > 0){
mysql_query("update student set password = '$password', status = 'Registered' where student_id = '$id'")or die(mysql_error());
$_SESSION['id']=$id;
echo 'true';
}else{
echo 'false';
}
?>
Firstly, you could use this code to check when the user stops typing:
Run javascript function when user finishes typing instead of on key up?
Once that is finished, this SQL code may work to check if the email already exists:
SELECT EXISTS(SELECT email FROM email_table)
Then you can simply use a conditional statement to print whether the email exists.

Getting the form to submit/ email

I'm trying to figure this stuff out as I'm going so some expert help and advice would be appreciated. I have a form - using jQuery and Ajax, at the moment I dont know whats working - like if I submit it echos back the data input (only one field - still need to figure out how to add more to the code) but nothing comes through to my email. Am I supposed to link it to some other PHP validation script or can it all be in one place?
Here is a link to the test space: www.bgv.co.za/testspace/contactos.php
Here is the PHP: (my syntax is probably off) - Its a combination of Validation and AJAX stuff - file is called: post.php
<?php
$subject = "Website Contact Form Enquiry";
//If the form is submitted
if(isset($_POST['submit'])) {
//Check to make sure that the name field is not empty
if(trim($_POST['contactname']) == '') {
$hasError = true;
} else {
$name = trim($_POST['contactname']);
}
//Check to make sure sure that a valid email address is submitted
if(trim($_POST['email']) == '') {
$hasError = true;
} else if (!eregi("^[A-Z0-9._%-]+#[A-Z0-9._%-]+\.[A-Z]{2,4}$", trim($_POST['email']))) {
$hasError = true;
} else {
$email = trim($_POST['email']);
}
//Check to make sure comments were entered
if(trim($_POST['message']) == '') {
$hasError = true;
} else {
if(function_exists('stripslashes')) {
$comments = stripslashes(trim($_POST['message']));
} else {
$comments = trim($_POST['message']);
}
}
//If there is no error, send the email
if(!isset($hasError)) {
$emailTo = 'info#bgv.co.za'; //Put your own email address here
$body = "Name: $name \n\nEmail: $email \n\nComments:\n $comments";
$headers = 'From: My Site <'.$emailTo.'>' . "\r\n" . 'Reply-To: ' . $email;
mail($emailTo, $subject, $body, $headers);
$emailSent = true;
}
}
sleep(3);
if (empty($_POST['email'])) {
$return['error'] = true;
$return['msg'] = 'You did not enter you email.';
}
else {
$return['error'] = false;
$return['msg'] = 'You\'ve entered: ' . $_POST['email'] . '.';
}
echo json_encode($return);
?>
Here is the JS file (Called: ajaxSubmit)
$(document).ready(function(){
$('#submit').click(function() {
$('#waiting').show(500);
$('#contactform').hide(0);
$('#message').hide(0);
$.ajax({
type : 'POST',
url : 'post.php',
dataType : 'json',
data: {
email : $('#email').val()
},
success : function(data){
$('#waiting').hide(500);
$('#message').removeClass().addClass((data.error === true) ? 'error' : 'success')
.text(data.msg).show(500);
if (data.error === true)
$('#contactform').show(500);
},
error : function(XMLHttpRequest, textStatus, errorThrown) {
$('#waiting').hide(500);
$('#message').removeClass().addClass('error')
.text('There was an error.').show(500);
$('#contactform').show(500);
}
});
return false;
});
});
and here is the HTML DOC:
<?php
/**
* #author Brett Vorster <www.kreatif.co.za>
*/
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<meta name="description" content="Orchard Systems 2012 Symposium Register Here" />
<meta name="keywords" content="Orchard Systems, Fruit Growers" />
<title>Orchard Systems 2012 | Contact Form</title>
<link rel="stylesheet" type="text/css" media="all" href="css/style.css" />
<!--[if IE 7]>
<link rel="stylesheet" type="text/css" media="all" href="css/styleie7.css" />
<![endif]-->
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js" type="text/javascript"></script>
<script src="jquery.validate.pack.js" type="text/javascript"></script>
<script type="text/javascript">
$(document).ready(function(){
$('#contactform').validate({
showErrors: function(errorMap, errorList) {
//restore the normal look
$('#contactform div.xrequired').removeClass('xrequired').addClass('_required');
//stop if everything is ok
if (errorList.length == 0) return;
//Iterate over the errors
for(var i = 0;i < errorList.length; i++)
$(errorList[i].element).parent().removeClass('_required').addClass('xrequired');
},
submitHandler: function(form) {
$('h1.success_').removeClass('success_').addClass('success_form');
$("#content").empty();
$("#content").append("<div id='sadhu'>This is just plain text. I need me a variable of somethink</div>");
$('#contactform').hide();
var usr = document.getElementById('contactname').value;
var eml = document.getElementById('email').value;
var msg = document.getElementById('message').value;
document.getElementById('out').innerHTML = usr + " " + eml + msg;
document.getElementById('out').style.display = "block";
form.submit();
}
});
});
</script>
<link rel="shortcut icon" type="image/x-icon" href="/favicon.ico">
</head>
<body class="contact">
<div id="container">
<div class="sidebar">
<img src="images/orchardsystems2012.png" title="Orchard Systems 2012 Logo" />
<div class="data"><p>
10th International<br/>Symposium on<br/>Orchard Systems</p></div>
<div class="location"><p>
Stellenbosch<br/>South Africa<br/><span>3 - 6 December</span><br/>2012</p>
</div><a><img class="button" src="images/button_interested.png" title="I am interested - keep me informed" /></a>
<img class="button" src="images/button_attend.png" title="I want to attend - registration form" />
<a href="abstract.html" title="Click here to submit an abstract" ><img class="button" src="images/button_abstract.png" title="I want to take part - submit an abstract" /></a>
<img src="images/ishslogo.gif" style="margin:45px 63px 0px 63px;" />
</div>
<div id="intainer">
<div id="menu">
<ul>
<li><a href="index.html" tabindex="i" title="Orchard Systems 2012 | Home" >Home</a></li>
<li><a href="aboutus.html" tabindex="au" title="About Us" >About Us</a></li>
<li><a href="programme.html" tabindex="p" title="Programme" >Programme</a></li>
<li><a href="registration.html" tabindex="r" title="Registration Form" >Registration</a></li>
<li><a href="venue.html" tabindex="v" title="Venue" >Venue</a></li>
<li><a href="accommodation.html" tabindex="a" title="Accommodation" >Accommodation</a></li>
<li>Tours</li>
<li class="current">Contact</li>
</ul>
</div>
<div class="header">
<h3 class="pagetitle">Contact</h3>
</div>
<div id="content">
<p class="general_site">If you want to be kept in the loop please send us your details and we will update you. Suggestions for workshops are welcome.</p>
<div id="message" style="display: none;">
</div>
<div id="waiting" style="display: none;">
Please wait<br />
<img src="images/ajax-loader.gif" title="Loader" alt="Loader" />
</div>
<form action="" id="contactform" method="post">
<fieldset>
<legend>Demo form</legend>
<div class="_required"><label for="name">Name*</label><input type="text" size="50" name="contactname" id="contactname" value="" class="required" /></div><br/><br/>
<div class="_required"><label for="email">E-mail address*</label><input type="text" size="50" name="email" id="email" value="" class="required email" /></div><br/><br/>
<label for="message">Message</label><textarea rows="5" cols="50" name="message" id="message" class="required"></textarea><br/>
<div class="checko"><input type="checkbox" class="check" name="ISHS Member"/><label class="right" for="message">I am interested in a pre-symposium tour</label></div>
<input type="submit" value="submit" name="submit" id="submit" />
</fieldset>
</form>
<p class="general_site">Or you can contact Retha Venter on +27 82 6567088 or reventer#netactive.co.za</p>
</div>
</div>
</div>
<div id="footer">
<div class="footer_content">
<div class="copyright"><a href="http://www.kreatif.co.za" target="_blank" title="website designed and developed by Kreatif Code.Design">© Orchard Systems 2012<br/>
Designed by kreatif.co.za</a></div>
<span class="contactno">Tel +27 21 000 0000</span>
<span class="emailus">info#orchardsystems2012.co.za</span>
</div>
</div>
<script type="text/javascript" src="js/ajaxSubmit.js"></script>
</body>
</html>
Please help me, I've spent the whole weekend trying to find a way to do this. Everytime I feel like I get somewhere and it amounts to nothing... I'm no programmer I dont understand how all of this works but I am learning and just really need to know how to do it. Thank you
Sorted by adding this to the PHP file >
//If there is no error, send the email
if(!isset($hasError)) {
$emailTo = 'info#bgv.co.za'; //Put your own email address here
$body = "Name: $name \n\nEmail: $email \n\nComments:\n $comments";
$headers = 'From: My Site <'.$emailTo.'>' . "\r\n" . 'Reply-To: ' . $email;
mail($emailTo, $subject, $body, $headers);
$emailSent = true;
}
and this >
$subject = "Website Contact Form Enquiry";
$return['error'] = false;
$name = trim($_POST['name']);
$email = trim($_POST['email']);
$comments = trim($_POST['message']);
hey looks like I'm learning how this stuff works!