I'm working with the form using phpmailer. here phpmailer is working fine but before sending a mail I want to validate my form using js.validation is not working how should I validate the form before sending a mail using js. where I have to write a condition for this can anyone help me out I tried in many ways but didn't achieve it.
Below is my code
HTML
<form method="post" action="script.php" id="test" novalidate>
<div class="detail">
<label>name:</label>
<input type="text" name="user_name" data-validation="name" />
</div><!--detail-->
<div class="detail">
<label>Email:</label>
<input type="email" name="user_email" data-validation="email"/>
</div><!--detail-->
<div class="detail">
<label>phone</label>
<input type="number" name="user_phone" data-validation="phone" />
</div><!--detail-->
<div class="detail">
<label></label>
<input type="text" name="user_enquiry" data-validation="message" />
</div><!--detail-->
<div class="detail message">
<label>Message:</label>
<textarea name="user_message" cols="30" rows="15" data-validation="message"></textarea>
</div><!--detail-->
<p><input type="submit" name="send" id="send" value="Send" onclick="formSubmit();" /></p>
<div class="success_msg">
<p>Form submitted Successfully</p>
</div>
</form>
JS:
function formSubmit(){
var Validator = function(formObject) {
this.form = $(formObject);
var Elements = {
name: {
reg: /^[a-zA-Z]{2,20}$/,
require : true,
error: "Not a valid name.",
},
email: {
reg: /^[a-z-0-9_+.-]+\#([a-z0-9-]+\.)+[a-z0-9]{2,7}$/i,
error: "Not a valid e-mail address.",
},
phone: {
reg: /^\(?([0-9]{3})\)?[-. ]?([0-9]{3})[-. ]?([0-9]{4})$/,
error: "Not a valid number.",
},
message: {
reg: /^(?!\s*$).+/,
error: "Message field cannot be empty.",
},
gender: {
error: "gender is required",
},
selectOption: {
error: "this field is required",
required: true
}
};
var handleError = function(element, message) {
element.addClass('input-error');
var $err_msg = element.parent('div');
$err_msg.find('.error').remove();
var error = $('<div class="error"></div>').text(message);
error.appendTo($err_msg);
console.log(element);
element.on('keypress change', function() {
$(error).fadeOut(1000, function() {
console.log(element);
element.removeClass('input-error');
});
});
};
/* Select Option */
this.validate = function() {
var errorCount = 0;
this.form.find("select").each(function(index, field){
var type = $(field).data("validation");
var validation = Elements[type];
if($(field).val() == "") {
errorCount++;
handleError($(field), validation.error);
}
});
this.form.find("input, textarea").each(function(index, field){
var type = $(field).data("validation");
var validation = Elements[type];
if(validation !== undefined) {
var re = new RegExp(validation.reg);
if (validation){
if (!re.test($(field).val())){
errorCount++;
handleError($(field), validation.error);
}
}
}
})
/* Radio button */
var radioList = $('input:radio');
var radioNameList = new Array();
var radioUniqueNameList = new Array();
var notCompleted = 0;
for(var i=0; i< radioList.length; i++){
radioNameList.push(radioList[i].name);
}
radioUniqueNameList = jQuery.unique( radioNameList );
console.log(radioUniqueNameList);
for(var i=0; i< radioUniqueNameList.length; i++){
var field = $('#' + radioUniqueNameList[i]);
var type = field.data("validation");
var validation = Elements[type];
if($('input[name='+type+']:checked', '#test').val() == undefined) {
errorCount++;
handleError($(field), validation.error);
}
}
return errorCount == 0;
};
};
/* Submit form*/
$(function(){
$('form#test').on('submit', function (e) {
var NoErrors = new Validator(this).validate();
if(NoErrors == true) {
$.ajax({
url: this.action,
type: this.method,
data: $(this).serialize(),
success: function() {
// AJAX request finished, handle the results and error msg
$('.success_msg').fadeIn().delay(3000).fadeOut();
//$('input[type=text], input[type=number], input[type=email], textarea').val('').removeClass('error');
$('input[type!="submit"], textarea').val('').removeClass('error');
//this.reset();
}
});
}
return false;
})
})
}//formSubmit
PHP:
<?php
include "classes/class.phpmailer.php";
$mail = new PHPMailer; // Passing `true` enables exceptions
$mail->IsSMTP(); // Set mailer to use SMTP
$mail->SMTPDebug = 1; // Enable verbose debug output
$mail->SMTPAuth = true; // Enable SMTP authentication
$mail->SMTPSecure = 'tls'; // Enable TLS encryption, `ssl` also accepted
$mail->Host = 'smtp.gmail.com'; // Specify main and backup SMTP servers
$mail->Port = 587; // TCP port to connect to
$mail->IsHTML(true); // Set email format to HTML
$mail->Username = '***********'; // SMTP username
$mail->Password = '**********'; // SMTP password
$mail->SetFrom('**************');
$msg = 'Name : ' . $_POST["user_name"] . '<br> Email : ' . $_POST["user_email"] . '<br> Phone : ' . $_POST["user_phone"] . '<br> Enquiry : ' . $_POST["user_enquiry"] . '<br> Message : ' . $_POST["user_message"];
$mail->Subject = "subject here";
$mail->Body = $msg;
$mail->AddAddress($_POST["user_email"]);
if(!$mail->Send()){
echo 'Mailer Error: ' . $mail->ErrorInfo;
}else{
echo 'Message has been sent with using SMTP.';
}
?>
Related
This is index.php
Right now all i can do is give values to the $mail->Subject and $mail->body but i want it to be dynamic for example
Here i want to give 2 inputs for subject and message and pass it on $mail->Subject and $mail->Body
since the post method is on ajax im unable to pass two values from input fields to the send_mail.php any help would be appreciated
<?php
//index.php
$connect = new PDO("mysql:host=localhost;dbname=testing", "root", "");
$query = "SELECT * FROM customer ORDER BY customer_id";
$statement = $connect->prepare($query);
$statement->execute();
$result = $statement->fetchAll();
?>
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" />
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
</head>
<body>
<br />
<div class="container">
<br />
<div class="table-responsive">
<table class="table table-bordered table-striped">
<tr>
<th>Customer Name</th>
<th>Email</th>
<th>Select</th>
<th>Action</th>
</tr>
<?php
$count = 0;
foreach($result as $row)
{
$count = $count + 1;
echo '
<tr>
<td>'.$row["customer_name"].'</td>
<td>'.$row["customer_email"].'</td>
<td>
<input type="checkbox" name="single_select" class="single_select" data-email="'.$row["customer_email"].'" data-name="'.$row["customer_name"].'" />
</td>
<td>
<button type="button" name="email_button" class="btn btn-info btn-xs email_button" id="'.$count.'" data-email="'.$row["customer_email"].'" data-name="'.$row["customer_name"].'" data-action="single">Send Single</button>
</td>
</tr>
';
}
?>
<tr>
<td colspan="3"></td>
<td><button type="button" name="bulk_email" class="btn btn-info email_button" id="bulk_email" data-action="bulk">Send Bulk</button></td></td>
</tr>
</table>
</div>
</div>
</body>
</html>
<script>
$(document).ready(function(){
$('.email_button').click(function(){
$(this).attr('disabled', 'disabled');
var id = $(this).attr("id");
var action = $(this).data("action");
var email_data = [];
if(action == 'single')
{
email_data.push({
email: $(this).data("email"),
name: $(this).data("name")
});
}
else
{
$('.single_select').each(function(){
if($(this).prop("checked") == true)
{
email_data.push({
email: $(this).data("email"),
name: $(this).data('name')
});
}
});
}
$.ajax({
url:"send_mail.php",
method:"POST",
data:{email_data:email_data},
beforeSend:function(){
$('#'+id).html('Sending...');
$('#'+id).addClass('btn-danger');
},
success:function(data){
if(data == 'ok')
{
$('#'+id).text('Success');
$('#'+id).removeClass('btn-danger');
$('#'+id).removeClass('btn-info');
$('#'+id).addClass('btn-success');
}
else
{
$('#'+id).text(data);
}
$('#'+id).attr('disabled', false);
}
})
});
});
</script>
And this is send_mail.php
<?php
//send_mail.php
if(isset($_POST['email_data']))
{
require 'class/class.phpmailer.php';
$output = '';
foreach($_POST['email_data'] as $row)
{
$mail = new PHPMailer;
$mail->IsSMTP();
$mail->Host = 'smtp.gmail.com';
$mail->Port = '587';
$mail->SMTPAuth = true;
$mail->Username = 'xx';
$mail->Password = 'xx';
$mail->SMTPSecure = 'tls';
$mail->From = 'xx';
$mail->FromName = 'xx';
$mail->AddAddress($row["email"], $row["name"]);
$mail->WordWrap = 50;
$mail->IsHTML(true);
$mail->Subject = 'i want input to be passed here';
//An HTML or plain text message body
$mail->Body = 'and the body message to be passed here';
$mail->AltBody = '';
$result = $mail->Send(); //Send an Email. Return true on success or false on error
// if($result["code"] == '400')
// {
// $output .= html_entity_decode($result['full_error']);
// }
}
if($output == '')
{
echo 'ok';
}
else
{
echo $output;
}
}
?>
I am assuming You want to add two inputs for subject and message for each email data.
You can add 2 fields and in ajax set it along with email data and pass it to send_mail.php.
JS Code
<script>
$(document).ready(function(){
$('.email_button').click(function(){
$(this).attr('disabled', 'disabled');
var id = $(this).attr("id");
var action = $(this).data("action");
var email_data = [];
if(action == 'single')
{
email_data.push({
email: $(this).data("email"),
name: $(this).data("name"),
subject: $(this).data("subject"), //or can be grab from input
message: $(this).data("message")
});
}
else
{
$('.single_select').each(function(){
if($(this).prop("checked") == true)
{
email_data.push({
email: $(this).data("email"),
name: $(this).data('name'),
subject: $(this).data("subject"), //or can be grab from input
message: $(this).data("message")
});
}
});
}
$.ajax({
url:"send_mail.php",
method:"POST",
data:{email_data:email_data},
beforeSend:function(){
$('#'+id).html('Sending...');
$('#'+id).addClass('btn-danger');
},
success:function(data){
if(data == 'ok')
{
$('#'+id).text('Success');
$('#'+id).removeClass('btn-danger');
$('#'+id).removeClass('btn-info');
$('#'+id).addClass('btn-success');
}
else
{
$('#'+id).text(data);
}
$('#'+id).attr('disabled', false);
}
})
});
});
</script>
In send_mail.php replace following lines
$mail->Subject = 'i want input to be passed here';
//An HTML or plain text message body
$mail->Body = 'and the body message to be passed here';
With This
$mail->Subject = $row["subject"];
$mail->Body = $row["message"];
Hope it will answer your question.
Firt of all:
Send only user id with ajax (better use fetch() for requests in js)
and then get user data in file (send_mail.php) from database (user validation)!!!
User validation is needed if not by session then by checking against the database.
See composer class for sending emails with phpmailer here:
https://github.com/MoovFun/Xo-Mail
I am trying to validate a captcha code field so if the code they enter is correct it will take them to a thank you page with the download link, but if the security code they entered is incorrect then they will see a sorry message and to return back to previous page.
The issue I am facing is when I enter the captcha into this field and click submit the data is always no.
My form is a as follows:
<form action="" name="downloadform" id="downloadform" class="downloadform" method="post">
<div class="field">
<input name="name" type="text" id="name" class="input name" placeholder="Name..." />
</div>
<div class="field">
<input name="company" type="text" id="company" class="input company" placeholder="Company..." />
</div>
<div class="field">
<input name="tel" type="text" id="tel" class="input tel" placeholder="Telephone..." />
</div>
<div class="field">
<input name="email" type="text" id="email" class="input email" placeholder="Email Address..." />
</div>
<div class="field">
<img src="/CaptchaSecurityImages.php" alt="Captcha" class="captcha" />
<input type="text" name="sec_code" id="sec_code" class="input sec_code" placeholder="Please enter the characters above" />
</div>
<div class="field">
<div class="medium secondary btn"><input type="submit" name="Submit2" value="Send Request" class="btn" id="downloadbtn" /></div>
<input type="hidden" name="product" id="product" class="product" value="<?php echo $page[3]; ?>" />
</div>
</form>
My ajax form file looks like this:
$(function() {
filter = /^([a-zA-Z0-9_\.\-])+\#(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/;
$("#downloadbtn").click(function() {
var name = $("#name").val();
var company = $("#company").val();
var tel = $("#tel").val();
var email = $("#email").val();
var product = $("#product").val();
var sec_code = $("#sec_code").val();
if (name == "") {
$("#name").focus();
$("#name").val("");
$("#name").css({background:"#b72a18", color:"#fff"});
return false;
}
if (company == "") {
$("#company ").focus();
$("#company ").val("");
$("#company ").css({background:"#b72a18", color:"#fff"});
return false;
}
if (tel == "") {
$("#tel").focus();
$("#tel").val("");
$("#tel").css({background:"#b72a18", color:"#fff"});
return false;
}
if (!filter.test(email)) {
$("#email").focus();
$("#email").val("");
$("#email").css({background:"#b72a18", color:"#fff"});
return false;
}
if (product == "") {
$("#product").focus();
$("#product").val("");
$("#product").css({background:"#b72a18", color:"#fff"});
return false;
}
if (sec_code == "") {
$("#sec_code").focus();
$("#sec_code").val("");
$("#sec_code").css({background:"#b72a18", color:"#fff"});
return false;
}
$('.downloadform').html('<center><img src="/images/ajax-loader.gif" style="padding:20px;"></center>');
var dataString = '&name=' + name + '&tel=' + tel + '&company=' + company + '&email=' + email + '&product=' + product + '&sec_code=' + sec_code + '&type=download';
//alert (dataString);return false;
$.ajax({
type: "POST",
url: "/process_download.php",
data: dataString,
datatype: 'json',
success: function(data) {
$('.downloadform').html('<center><img src="/images/ajax-loader.gif" style="padding:20px;"></center>')
.hide()
.fadeIn(1500, function() {});
setTimeout(function ()
{
$(window.location).attr('href', '/process.php?download=' + data.product + '&sec_code=' + data.sec_code);
}, 2000);
}
});
return false;
});
});
Then I have my process download file:
<?php
session_start();
header("Content-type: application/json");
ob_start();
include('inc/connection.php');
$product = $_POST['product'];
$sec_code = $_SESSION['security_code'] == $_POST['sec_code'] ? 'yes' : 'no';
ob_end_clean();
$data = array('product'=>$product,'sec_code'=>$sec_code);
print json_encode($data);
die();
?>
Then the final process:
<?php
session_start();
include('inc/connection.php');
$sec_code = $_GET['sec_code'];
$proddownlink = $_GET['download'];
$proddownl = str_replace("_", " ", $_GET['download']);
$proddownl = ucwords($proddownl);
if ($sec_code == 'no') {
$message = '<p>Security code is wrong. Please click here to return back.</p>';
} else {
$message = '<p>Thank you for downloading ' . $proddownl . ' Data Sheet.</p>
<p>Please click here to download ' . $proddownl . ' PDF.</p>';
include_once('inc/connection.php');
include_once('inc/class.phpmailer.php');
$name = $_POST['name'];
$company = $_POST['company'];
$tel = $_POST['tel'];
$email = $_POST['email'];
$product = $_POST['product'];
$sec_code = $_POST['sec_code'];
$type = $_POST['type'];
$bodytext = "<ul>
<li><strong>Name:</strong> $name</li>
<li><strong>Company:</strong> $company</li>
<li><strong>Telephone Number:</strong> $tel</li>
<li><strong>Email Address:</strong> $email</li>
<li><strong>Area of Interest:</strong> $product</li>
</ul>";
$subject = "New Enquiry";
$query = "insert into user_email set name = '$name', email = '$email', tel = '$tel', type = '$type', message = '$bodytext'";
$result = $conn->query($query);
if(!$result) die($conn->error);
$mail = new PHPMailer(); // defaults to using php "mail()"
$body = $bodytext;
$mail->From = "sales#fidelitysystems.co.uk";
$mail->FromName = $name;
$mail->Subject = $subject;
$mail->AltBody = "To view the message, please use an HTML compatible email viewer!";
$mail->MsgHTML($body);
#$mail->AddAddress("sales#fidelitysystems.co.uk");
$mail->AddAddress("craig#arrivaldesign.co.uk");
$mail->IsSMTP();
$mail->SMTPAuth = "true";
$mail->Username = "postmaster#arrivalbusiness.co.uk";
$mail->Password = "edward";
$mail->Host = "mail.arrivalbusiness.co.uk";
$mail->Port = 587;
if(!$mail->Send()) {
echo "Mailer Error: " . $mail->ErrorInfo;
}
}
?>
In my quest to validate a form with PHP and $.ajax() and send a mail to my own mail adress having as sender my own gmail adress, as subject the user name and email from the form. Bassically I want the site to notify me that an user left me a message along with his name and adress si I can answer to him. When I try to send I receive an error.
I took the script from PHPMailer example but I cannot figure out where the mail body should be. I have the php file:
<?php
error_reporting(E_ALL);
ini_set('display_errors',true);
// require_once 'class.phpmailer.php';
require 'PHPMailerAutoload.php';
sleep(1);
$mail_reg = '/^(?i)(([^<>()[\]\\.,;:\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,}))$/';
$return = array();
$mesaj = '';
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
if (empty($_POST['inputName']) || is_numeric($_POST['inputName'])) {
$mesaj = "Please enter your name!";
// $return['error'] = true;
$return['msg'] = 'oops'.$mesaj;
echo json_encode($return);
exit();
} elseif (empty($_POST['inputEmail']) || !preg_match($mail_reg, $_POST['inputEmail'])) {
$mesaj = "Please enter your e-mail!";
// $return['error'] = true;
$return['msg'] = 'oops'.$mesaj;
echo json_encode($return);
exit();
} elseif (empty($_POST['inputMess'])) {
$mesaj = "Please tell us something";
// $return['error'] = true;
$return['msg'] = 'oops'.$mesaj;
echo json_encode($return);
exit();
} else {
$mail = new PHPMailer();
$mail->IsSMTP();
$mail->SMTPDebug = 2;
$mail->Debugoutput = 'html';
$mail->Host = "smtp.gmail.com";
$mail->Port = 587;
$mail->SMTPSecure = "tls";
$mail->SMTPAuth = true;
$mail->Username = "tavitudor124#gmail.com";
$mail->Password = "**********";
$mail->SetFrom('tavitudor124#gmail.com' , 'First Last');
$mail->Subject = $_POST['inputName'].'/'.$_POST['inputEmail'].'wrote';
//$mail->MsgHTML($body);
$address = 'tavi_tudor#yahoo.com';
$mail->AddAddress($address, "John Doe");
$mail->Body = $_POST['inputMess'];
if (!$mail->Send()) {
$mesaj = 'The message cannot be delivered, please try again later!';
$return['msg'] = 'The message cannot be delivered, please try again later!';
echo json_encode($return);
exit();
} else {
$mesaj = 'Thank you for getting in touch. We will contact you!';
// $return["error"] = false;
$return["msg"] = 'Thank you for getting in touch. We will contact you! '.$mail- >ErrorInfo;
echo json_encode($return);
exit();
}
}
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>NRDC Environmental N.G.O.</title>
<link href="css/bootstrap.css" rel="stylesheet">
<script src="//cdnjs.cloudflare.com/ajax/libs/jquery/1.8.2/jquery.min.js"></script>
<script src="js/bootstrap.min.js"></script>
<script src="js/marin.js"></script>
</head>
<div class="site-wrapper">
<div class="site-wrapper-inner">
<div class="cover-container">
<div class="masthead clearfix">
<div class="inner">
<h3 class="masthead-brand">NRDC<br />Save our Planet O.N.G.</h3>
<ul class="nav masthead-nav">
<li>Home</li>
<li>Gallery</li>
<li class="active">Contact</li>
<li>Join Us</li>
</ul>
</div>
</div>
<div class="inner cover">
<div class="row">
<div class="col-xs-12" style="text-align:center;font-size:22px;">
<form method="POST" action="<?php echo $_SERVER['PHP_SELF']; ?>">
<div class="form-group">
<label for="inputName">Your name</label>
<input type="text" name="inputName" class="form-control" id="inputName" placeholder="Name">
</div>
<div class="form-group">
<label for="inputEmail">Your e-mail</label>
<input type="text" name="inputEmail" class="form-control" id="inputEmail" placeholder="E-mail">
</div>
<div class="form-group">
<label for="inputMess">Your message for us</label>
<textarea name="inputMess" class="form-control" id="inputMess"> </textarea>
</div>
<button type="submit" name="send" class="btn btn-default">Send</button>
</form>
<div id='mess'> </div>
</div>
</div>
</div>
<div class="mastfoot">
<div class="inner">
<p id="footer">©All rights reserved to NRDC, by TaoAppz</p>
</div>
</div>
</div>
</div>
</div>
JS
$(document).ready(function() {
var email_reg = /^(([^<>()[\]\\.,;:\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,}))$/i;
$('form').submit(function(event) {
event.preventDefault();
if ($('#inputName').val() == '' || $('#inputName').val().length < 2 || !isNaN($('#inputName').val())) {
alert('Please enter your name');
} else if (!email_reg.test($('#inputEmail').val())) {
alert('Please enter a valid e-mail adress');
} else if ($('#inputMess').val() == '' || !isNaN($('#inputMess').val())) {
alert('Please tell us something');
} else {
var formData = $('form').serialize();
submitForm(formData);
}
})
function submitForm(formData) {
$.ajax({
type: 'POST',
url: $('form').action,
data: formData,
dataType: 'json',
cache: false,
timeout: 7000,
beforeSend: function() {
$('#mess').text('Processing...');
},
success: function(data) {
$('#mess').text(data.msg);
},
error: function(XMLHttpRequest, textStatus, errorThrown) {
$('#mess').text('Error! ' + textStatus + ' ' + errorThrown + ' ' + 'Please try again later!');
},
complete: function(XMLHttpRequest, status) {
//$('form')[0].reset();
}
})
}
})
It was a mistake on my include in php and the '$mail->Debugoutput = 'html' created html output that was pasrsed as JSON.
So I took out the debugg mode from PHPMailer and now I have a nice working contact form using ajax and PHPMailer. Thanks for your help
I'm trying to validate a contact form with jquery and php but I always get false from php even though it's working fine. I'm going to explain with my code:
This is my html:
<form method='post'>
<label>Name<input id="name" type="text" name="name" /></label>
<label>Email Address<input id="email" type="text" name="email" /></label>
<label>Subject<input id="subject" type="text" name="subject" /></label>
<label>Message<textarea id="message" name="message"></textarea></label>
<label><input type="button" value="Submit Form" id="button_form" /></label>
</form>
This is my js code:
function validaForm(){
// Campos de texto
if($('#email').val() == ""){
alert("You must fill in at least the email field.");
$('#email').focus();
return false;
}
return true;
}
$('#button_form').click( function() {
if(validaForm()){
$.post("php/form.php",$('form').serialize(),function(res){
if(res == 1){
alert("Your e-mail has been sent, Thank you for contacting us. We will answer you as soon as possible.");
} else if(res == 0){
alert("Sorry, your e-mail couldn't been sent, please try again later.");
} else {
alert("Others.");
}
});
}
});
This is my .php file:
<?php
require 'class.phpmailer.php';
$mail = new PHPMailer();
$mail->IsSMTP();
$mail->Host = 'smtp.domain.com';
$mail->SMTPAuth = true;
$mail->Username = 'myacc#mydomain.com';
$mail->Password = 'pass';
$mail->SMTPSecure = 'tls';
$mail->From = 'myacc#mydomain.com';
$mail->FromName = 'Contact Form';
$mail->AddAddress('myacc#mydomain.com');
$mail->AddAttachment('/var/tmp/file.tar.gz');
$mail->AddAttachment('/tmp/image.jpg', 'new.jpg');
$mail->IsHTML(true);
$mail->Subject = $_POST['subject'];
$mensajeFinal = "Message";
$mail->Body = $mensajeFinal;
if(!$mail->Send()) {
return false;
} else {
return true;
};
?>
Ok, Everything is working fine, I mean, it sends the e-mail but the problem is that I always get false from php file no matter if it sends or not the e-mail.
Am I doing something wrong?? Is there something I am missing??
I would appreciate any help. Thanxs a lot.
You have to use echo here, this is not function. return is used for returning result from functions. Also remove the ; after
else {...};
^
if(!$mail->Send()) {
echo false;
} else {
echo true;
}
In your click function
$('#button_form').click( function() { .... } );
Be sure to return false if validaForm returns false
Hi put your code between
$(document).ready(function() {
});
Looks like
$(document).ready(function() {
$('#button_form').click( function() {
if(validaForm()){
$.post("php/form.php",$('form').serialize(),function(res){
if(res == 1){
alert("Your e-mail has been sent, Thank you for contacting us. We will answer you as soon as possible.");
} else if(res == 0){
alert("Sorry, your e-mail couldn't been sent, please try again later.");
} else {
alert("Others.");
}
});
}
});
});
I've a simple working php/ajax contact form with validation. I'd like to clear all fields after VALID submission, so I tried $("#myform")[0].reset(); see in the code below. It clears the form nicely, but the problem is it also clears everything when the validation wasn't successful, which is really annoying.
Here's the HTML:
<form id="myform" method="post" action="sendEmail.php">
<div id="container">
<div id="main">
<p>Name / Company <span>*</span></p>
<input type="text" name="name" id="name" />
<p>Email Address <span>*</span><p>
<input type="text" name="email" id="email" />
<p>Offer / Message <span>*</span></p>
<textarea name="message" id="message" rows="6"></textarea>
<p><input type="submit" name="submit" id="submit" value="Send Request" /></p>
<p><ul id="response" /></p>
</div>
</div>
And the php:
<?php
$name = trim($_POST['name']);
$email = $_POST['email'];
$message = $_POST['message'];
$site_owners_email = 'sample#yahoo.com';
$site_owners_name = 'Joe';
if (strlen($name) < 3) {
$error['name'] = "* Please enter your name.";
}
if (!preg_match('/^[a-z0-9&\'\.\-_\+]+#[a-z0-9\-]+\.([a-z0-9\-]+\.)*+[a-z]{2}/is', $email)) {
$error['email'] = "* Please enter a valid email address";
}
if (strlen($message) < 4) {
$error['message'] = "* Please leave an offer / message.";
}
if (!$error) {
require_once('phpMailer/class.phpmailer.php');
$mail = new PHPMailer();
$mail->From = $email;
$mail->FromName = $name;
$mail->Subject = "Subject";
$mail->AddAddress($site_owners_email, $site_owners_name);
$mail->Body = $message;
$mail->Send();
echo "<li class='success'> Thanks for your request!<br> We will respond to you as soon as possible. </li>";
} # end if no error
else {
$response = (isset($error['name'])) ? "<li>" . $error['name'] . "</li> \n" : null;
$response .= (isset($error['email'])) ? "<li>" . $error['email'] . "</li> \n" : null;
$response .= (isset($error['message'])) ? "<li>" . $error['message'] . "</li>" : null;
echo $response;
} # end if there was an error sending
?>
At last, the js:
$(function() {
var paraTag = $('input#submit').parent('p');
$(paraTag).children('input').remove();
$(paraTag).append('<input type="button" name="submit" id="submit" value="Send Request" />');
$('#main input#submit').click(function() {
$('#main').append('<img src="images/ajax-loader.gif" class="loaderIcon" alt="Loading..." />');
var name = $('input#name').val();
var email = $('input#email').val();
var message = $('textarea#message').val();
$.ajax({
type: 'post',
url: 'sendEmail.php',
data: 'name=' + name + '&email=' + email + '&message=' + message,
success: function(results) {
$('#main img.loaderIcon').fadeOut(1000);
$('ul#response').html(results);
$("#myform")[0].reset();
}
}); // end ajax
});
});
I'm new to php and js, so I've pasted all of my code, to be easier for you if i did something wrong. Thanks for your help!
Well, a good idea is returning a JSON object form PHP, so you can check for errors on Javascript.
PHP:
$result = array(
"error" => false,
"html" => null
);
if(!$is_valid){
$result["error"] = true;
$result["html"] = "<b>Error</b>";
}else{
$result["error"] = false;
$result["html"] = "<b>Success</b>";
}
echo json_encode($result);
jQuery
$.ajax({
type: 'post',
url: 'url.php',
data: {/*put a cool data here*/},
dataType : "json", // return a json object
success: function(result) {
if(result.error){
/* On error stuff */
$("body").append(result.html);
}else{
/* On success stuff */
$("body").append(result.html);
}
}
});