This question already has answers here:
AJAX form not displaying succes or error message
(3 answers)
Closed 5 years ago.
I'm still learning the code languages that I used to create my form with. So I can't seem to figure out what seems to be the problem. Here's my code:
HTML:
<form action="mail.php" method="POST">
<ul class="form-style-1">
<li>
<input type="text" id="mail-name" name="name" class="field-divided" maxlength="15" placeholder="Voornaam *" /> <input type="text" id="mail-lastname" name="lastname" class="field-divided" maxlength="15" placeholder="Achternaam" >
</li>
<li>
<input type="email" id="mail-email" name="email" placeholder="E-mail *" class="field-long" maxlength="40" >
</li>
<li>
<input type ="text" id="mail-phone" name="phone" placeholder="Telefoonnummer" class="field-long" maxlength = "15">
</li>
<li>
<select name="subject" id="mail-subject" class="field-select" >
<option disabled value="" selected hidden >--Onderwerp-- *</option>
<option value="Kennismakingsgesprek">Kennismakingsgesprek</option>
<option value="Meer informatie">Meer informatie</option>
<option value="activiteit">Aanmelding activiteit</option>
<option value="Vraag/klacht">Vraag/klacht</option>
<option value="Contact">Overig</option>
</select>
</li>
<li>
<textarea name="information" id="mail-information" placeholder =" Je bericht *"class="field-long field-textarea" maxlength="2000"></textarea>
</li>
<button class="mail-submit" id="mail-submit" type="submit" name="submit">Send e-mail</button>
<span class="form-message"></span>
</ul>
</form>
JS:
$(document).ready(function() {
$('form').submit(function(event) {
event.preventDefault();
var name = $("#mail-name").val();
var name = $("#mail-lastname").val();
var email = $("#mail-email").val();
var phone = $("#mail-phone").val();
var subject = $("#mail-subject").val();
var information = $("#mail-information").val();
$(".form-message").load("mail.php", {
name: name,
lastname: lastname,
email: email,
phone: phone,
subject: subject,
information: information
});
});
});
**PHP: **
<?php
if (isset($_POST['submit'])) {
$email_to = "#";
$email_subject = "#";
$name = $_POST['name'];
$lastname = $_POST['lastname'];
$email = $_POST['email'];
$phone = $_POST['phone'];
$subject = $_POST['subject'];
$information = $_POST['information'];
$errorEmpty = false;
$errorEmail = false;
if (empty($name) || empty($lastname) || empty($email) || empty($phone) || empty($subject) || empty($information)) {
echo "<span class='form-error'>Voer alle velden in!</span>";
$errorEmpty = true;
}
elseif (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
echo "<span class='form-error'>Geef een geldig E-mail!</span>";
$errorEmail = true;
}
else {
$formcontent=" Naam: $name \n\n Achternaam: $lastname \n\n Email: $email \n\n Telefoon: $phone \n\n Onderwerp: $subject \n\n Informatie: $information";
$mailheader = "From: ".$_POST["email"]."\r\n";
$headers = "From: ". htmlspecialchars($_POST['name']) ." <" . $_POST['email'] . ">\r\n";
$headers .= "Reply-To: " . $_POST['email'] . "\r\n";
$headers .= "MIME-Version: 1.0\r\n";
$headers .= "Content-Type: text/html; charset=ISO-8859-1\r\n";
mail($email_to, $subject, $formcontent, $mailheader);
echo "<span class='form-success'>E-mail has been sent!</span>";
}
}
else {
echo "Not working!";
}
?>
I know for a fact that this line of code is stopping the form from basically doing anything:
$('form').submit(function (event) {
event.preventDefault();
Without this line of code, the form works. But instead of getting a display message under the form, it just sends you to an echo page with the text in it.
What I'm looking for is that the page doesn't refresh after the form has been sent, so that it can display the form-succes or error message.
Thank you for your time.
You should use ajax here like this for example on submit of your form just
$("#mail-submit").click(function(event){
event.preventDefault();
var name = $("#mail-name").val();
var lastname = $("#mail-lastname").val();
var email = $("#mail-email").val();
var phone = $("#mail-phone").val();
var subject = $("#mail-subject").val();
var information = $("#mail-information").val();
$.post("mail.php",
{
name: name,
lastname: lastname,
email: email,
phone: phone,
subject: subject,
information: information,
submit: "yes" // this is for your php if isset($_POST['submit'])
},
function(data){
$(".form-message").html( data ); // put return in html element
}
);
});
let me know if you need some more details
Related
I have form on my website, when I click the button I trigger a JS function that take the inputs from my form and send a mail using php. After the mail are sent a modal is showing a thanks for contact. Everything works perfect until I try to validate the form using "HTML5 required". And if I use the submit form the validation works but not my modal. This drives me crazy and it must be some easy solution that I miss. I have search a lot but don't find any solution that's fits my issue.
BR
Mats
MY HTML
<input type="text" name="name" id="name" required placeholder="Ditt namn:"><br>
<input type="email" name="mail" id="mail" required placeholder="Din e-post:"><br>
<input type="tel" name="phone" id="phone" required placeholder="Ditt telefonnummer:"><br>
<textarea name="message" id="message" required placeholder="Ditt meddelande:" rows="10"></textarea>
<table>
<td><input type="checkbox" name="checkbox" id="checkbox" value="checkbox" required ></td><td>
<label for="checkbox"> Jag har läst och godkänner news <a onclick="showModal('intrigitetspolicyModal')">integritetspolicy</a></label>
</td> <br>
</table>
<input id="buttonMail" type='button' onclick=”sendMail()” value='Skicka'/>
</form>
My JS
function sendMail(){
var data = {
name: $("#name").val(),
mail: $("#mail").val(),
phone: $("#phone").val(),
message: $("#message").val()
};
$.ajax({
type: "POST",
url: "javaScript/mail.php",
data: data,
success: function(){
}
});
showModal('kontaktModal');
$("#formMail").trigger('reset');
return false;
}
function showModal(Modal){
var modal = document.getElementById(Modal);
modal.style.display = "block";
}
MY PHP
<?php
if($_POST){
$to = "example#example";
$subject = "Medelande från example";
$subject2 = "Kopia på det formulär du skicka på example";
$name = $_POST['name'];
$from = $_POST['mail'];
$phone = $_POST['phone'];
$message = $name . " skrev:" . "\n\n" . $_POST['message'] . "\n\n" . $_POST['name'] . "\n" . $_POST['mail'] . "\n" . $_POST['phone'];
$message2 = "Här är en kopia på ditt meddelande " . $first_name . "\n\n" . $_POST['message'];
$headers = "From:" . $from;
$headers2 = "From:" . $to;
mail($to,$subject,$message,$headers); //send email
mail($from,$subject2,$message2,$headers2); // sends a copy of the message to the sender
}
?>
Basically, you just need to call reportValidity() on your sendMail() function to benefit from the HTML5 validation without actually triggering the form submit.
Something like this should work for you:
function sendMail(){
var isValid = document.querySelector('from').reportValidity();
if (!isValid) {
return false;
}
var data = {
name: $("#name").val(),
mail: $("#mail").val(),
phone: $("#phone").val(),
message: $("#message").val()
};
$.ajax({
type: "POST",
url: "javaScript/mail.php",
data: data,
success: function(){
}
});
showModal('kontaktModal');
$("#formMail").trigger('reset');
return false;
}
See more info/example here: https://googlechrome.github.io/samples/report-validity/
I Have 2 problems with this script, something is wrong
1. the email address value can't be selected from the database.
the script works only if I manually type the e-mail
$yourEmail = "email#exemple.com";
after I press the submit button, I want the page to refresh without the website link being changed or after i click send, the contact box should close.
Could you please help to solve these problems?
Thank you in advance!
<?php
$sql = "select * from tables where email='" . $email . "'";
while($row=mysql_fetch_array($sql))
{
$email=$row['email'];
}
$yourEmail = $email; // the email address you wish to receive these mails through
$yourWebsite = "WEBSITE NAME";
$thanksPage = ''; // URL to 'thanks for sending mail' page; leave empty to keep message on the same page
$maxPoints = 4;
$requiredFields = "name,email,comments";
$error_msg = array();
$result = null;
$requiredFields = explode(",", $requiredFields);
function clean($data) {
$data = trim(stripslashes(strip_tags($data)));
return $data;
}
function isBot() {
$bots = array("Indy", "Blaiz", "Java", "libwww-perl", "Python", "OutfoxBot", "User-Agent", "PycURL", "AlphaServer", "T8Abot", "Syntryx", "WinHttp", "WebBandit", "nicebot", "Teoma", "alexa", "froogle", "inktomi", "looksmart", "URL_Spider_SQL", "Firefly", "NationalDirectory", "Ask Jeeves", "TECNOSEEK", "InfoSeek", "WebFindBot", "girafabot", "crawler", "www.galaxy.com", "Googlebot", "Scooter", "Slurp", "appie", "FAST", "WebBug", "Spade", "ZyBorg", "rabaz");
foreach ($bots as $bot)
if (stripos($_SERVER['HTTP_USER_AGENT'], $bot) !== false)
return true;
if (empty($_SERVER['HTTP_USER_AGENT']) || $_SERVER['HTTP_USER_AGENT'] == " ")
return true;
return false;
}
if ($_SERVER['REQUEST_METHOD'] == "POST") {
if (isBot() !== false)
$error_msg[] = "No bots please! UA reported as: ".$_SERVER['HTTP_USER_AGENT'];
// lets check a few things - not enough to trigger an error on their own, but worth assigning a spam score..
// score quickly adds up therefore allowing genuine users with 'accidental' score through but cutting out real spam :)
$points = (int)0;
$badwords = array("adult", "beastial", "bestial", "blowjob", "clit", "cum", "cunilingus", "cunillingus", "cunnilingus", "cunt", "ejaculate", "fag", "felatio", "fellatio", "fuck", "fuk", "fuks", "gangbang", "gangbanged", "gangbangs", "hotsex", "hardcode", "jism", "jiz", "orgasim", "orgasims", "orgasm", "orgasms", "phonesex", "phuk", "phuq", "pussies", "pussy", "spunk", "xxx", "viagra", "phentermine", "tramadol", "adipex", "advai", "alprazolam", "ambien", "ambian", "amoxicillin", "antivert", "blackjack", "backgammon", "texas", "holdem", "poker", "carisoprodol", "ciara", "ciprofloxacin", "debt", "dating", "porn", "link=", "voyeur", "content-type", "bcc:", "cc:", "document.cookie", "onclick", "onload", "javascript");
foreach ($badwords as $word)
if (
strpos(strtolower($_POST['comments']), $word) !== false ||
strpos(strtolower($_POST['name']), $word) !== false
)
$points += 2;
if (strpos($_POST['comments'], "http://") !== false || strpos($_POST['comments'], "www.") !== false)
$points += 2;
if (isset($_POST['nojs']))
$points += 1;
if (preg_match("/(<.*>)/i", $_POST['comments']))
$points += 2;
if (strlen($_POST['name']) < 3)
$points += 1;
if (strlen($_POST['comments']) < 15 || strlen($_POST['comments'] > 1500))
$points += 2;
if (preg_match("/[bcdfghjklmnpqrstvwxyz]{7,}/i", $_POST['comments']))
$points += 1;
// end score assignments
foreach($requiredFields as $field) {
trim($_POST[$field]);
if (!isset($_POST[$field]) || empty($_POST[$field]) && array_pop($error_msg) != "Please fill in all the required fields and submit again.\r\n")
$error_msg[] = "Please fill in all the required fields and submit again.";
}
if (!empty($_POST['name']) && !preg_match("/^[a-zA-Z-'\s]*$/", stripslashes($_POST['name'])))
$error_msg[] = "The name field must not contain special characters.\r\n";
if (!empty($_POST['email']) && !preg_match('/^([a-z0-9])(([-a-z0-9._])*([a-z0-9]))*\#([a-z0-9])(([a-z0-9-])*([a-z0-9]))+' . '(\.([a-z0-9])([-a-z0-9_-])?([a-z0-9])+)+$/i', strtolower($_POST['email'])))
$error_msg[] = "That is not a valid e-mail address.\r\n";
if (!empty($_POST['url']) && !preg_match('/^(http|https):\/\/(([A-Z0-9][A-Z0-9_-]*)(\.[A-Z0-9][A-Z0-9_-]*)+)(:(\d+))?\/?/i', $_POST['url']))
$error_msg[] = "Invalid website url.\r\n";
if ($error_msg == NULL && $points <= $maxPoints) {
$subject = "Automatic Form Email";
$message = "You received this e-mail message through your website: \n\n";
foreach ($_POST as $key => $val) {
if (is_array($val)) {
foreach ($val as $subval) {
$message .= ucwords($key) . ": " . clean($subval) . "\r\n";
}
} else {
$message .= ucwords($key) . ": " . clean($val) . "\r\n";
}
}
$message .= "\r\n";
$message .= 'IP: '.$_SERVER['REMOTE_ADDR']."\r\n";
$message .= 'Browser: '.$_SERVER['HTTP_USER_AGENT']."\r\n";
$message .= 'Points: '.$points;
if (strstr($_SERVER['SERVER_SOFTWARE'], "Win")) {
$headers = "From: $yourEmail\r\n";
} else {
$headers = "From: $yourWebsite <$yourEmail>\r\n";
}
$headers .= "Reply-To: {$_POST['email']}\r\n";
if (mail($yourEmail,$subject,$message,$headers)) {
if (!empty($thanksPage)) {
header("Location: $thanksPage");
exit;
} else {
$result = 'Your mail was successfully sent.';
$disable = true;
}
} else {
$error_msg[] = 'Your mail could not be sent this time. ['.$points.']';
}
} else {
if (empty($error_msg))
$error_msg[] = 'Your mail looks too much like spam, and could not be sent this time. ['.$points.']';
}
}
function get_data($var) {
if (isset($_POST[$var]))
echo htmlspecialchars($_POST[$var]);
}
?>
html form
<form action="<?php echo basename(__FILE__); ?>" method="post">
<noscript>
<p><input type="hidden" name="nojs" id="nojs" /></p>
</noscript>
<p>
<label for="name">Name: *</label>
<input type="text" name="name" id="name" value="<?php get_data("name"); ?>" /><br />
<label for="email">E-mail: *</label>
<input type="text" name="email" id="email" value="<?php get_data("email"); ?>" /><br />
<label for="url">Website URL:</label>
<input type="text" name="url" id="url" value="<?php get_data("url"); ?>" /><br />
<label for="location">Location:</label>
<input type="text" name="location" id="location" value="<?php get_data("location"); ?>" /><br />
<label for="comments">Comments: *</label>
<textarea name="comments" id="comments" rows="5" cols="20"><?php get_data("comments"); ?></textarea><br />
</p>
<p>
<input type="submit" name="submit" id="submit" value="Send" <?php if (isset($disable) && $disable === true) echo ' disabled="disabled"'; ?> />
</p>
</form>
Before your while loop your suppose to actually perform the query with mysql_query or mysqli_query in your case mysql_query.
Your other problem is your fetching the results as an array which is index based (0...) and your using a string to access it so you should call mysql_fetch_assoc which returns an associative array which can be accessed in your current implementation
$sql = "select * from tables where email='" . $email . "'";
$result = mysql_query($sql, $connection);// this actually performs the query and returns the result to be fetched using mysql_fetch_array or it's other methods such as mysql_fetch_assoc
while($row=mysql_fetch_assoc($result)){
$email=$row['email'];
}
Also declare your $email variable outside the while loop as if no rows were returned from the database your $email variable won't exist therefore breaking your code so you should bring it to the top of the while loop and initialize it to some default value.
I'm creating a plugin for my contact form using ajax and add shortcode wordpress . I don't get how to do it and it work perfect, and read several forums about the admin- ajax.php but do not understand how to pass data to this file.
This is the code :
<?php
/*
Plugin Name: Formulario de contacto
Plugin URI: http://www.e-world.co
Description: Formulario de contacto con ajax
Version: 1.0
Author: Jorge Moreno
Author URI: http://www.e-world.co
license: GLP2
*/
function the_action_function(){
$adminemail = "jorge.moreno#e-world.co";
if ($_GET['send'] == 'comments')
{
$_uname = $_POST['name'];
$_uemail = $_POST['email'];
$_website = $_POST['website'];
$_comments = stripslashes($_POST['comment']);
$email_check = '';
$return_arr = array();
if($_uname=="" || $_uemail=="" || $_comments=="")
{
$return_arr["frm_check"] = 'error';
$return_arr["msg"] = "Please fill in all required fields!";
}
else if(filter_var($_uemail, FILTER_VALIDATE_EMAIL))
{
$to = $adminemail;
$from = $_uemail;
$subject = "Renew Email: " .$_uname;
$message = 'Name: ' . $_uname . '<br><br> Email: ' . $_uemail . '<br><br> website: ' . $_website . '<br><br> Comment: ' . $_comments;
$headers = "MIME-Version: 1.0\r\n";
$headers .= "Content-type: text/html; charset=iso-8859-1\r\n";
$headers .= "Content-Transfer-Encoding: 7bit\r\n";
$headers .= "From: " . $from . "\r\n";
#mail($to, $subject, $message, $headers);
} else {
$return_arr["frm_check"] = 'error';
$return_arr["msg"] = "Please enter a valid email address!";
}
echo json_encode($return_arr);
}
}
function createAjaxContactForm() {
return '
<div class="form">
<form action="process.php" method="post" name="ContactForm" id="ContactForm" >
<div class="form-group">
<input type="text" class="form-control" name="name" placeholder="Full Name *">
</div>
<div class="form-group">
<input type="text" class="form-control" name="email" placeholder="Email *">
</div>
<div class="form-group">
<input type="text" class="form-control" name="website" placeholder="Website">
</div>
<div class="form-group">
<textarea rows="5" class="form-control" name="comment" placeholder="Your Message *" style="height:175px;"></textarea>
</div>
<div id="message_post"></div>
<input class="btn btn-default" type="submit" value="ENVIAR" name="submitf" id="submitf">
</form>
</div>';
}
add_shortcode('AjaxContactForm', 'createAjaxContactForm');
?>
and my ajax:
jQuery(function(){
jQuery("#ContactForm").submit(function(){
jQuery("#submitf").value='Please wait...';
jQuery.post("password/wp-admin/admin-ajax.php", jQuery("#ContactForm").serialize(),
function(data){
if(data.frm_check == 'error'){
jQuery("#message_post").html("<div class='errorMessage'>ERROR: " + data.msg + "!</div>");
document.ContactForm.submitf.value='Resend >>';
document.ContactForm.submitf.disabled=false;
} else {
jQuery("#message_post").html("<div class='successMessage'>Your message has been sent successfully!</div>");
jQuery("#submitf").value='Send >>';
}
}, "json");
return false;
});
});
This is ajaxurl write this code your-theme/functions.php
<?php function frontend_custom_ajaxurl() { ?>
<script type="text/javascript">
var ajaxurl = '<?php echo admin_url('admin-ajax.php'); ?>';
</script>
<?php
}
add_action('wp_head','frontend_custom_ajaxurl');
This is your php function can do anything. And also write this code in your-theme/functions.php file
function your_function() {
parse_str($_POST['data'], $params);
print_r($params)
exit;
}
add_action('wp_ajax_your_function', 'your_function');
add_action('wp_ajax_nopriv_your_function', 'your_function');
This is JQuery.
jQuery("#ContactForm").submit(function(event) {
event.preventDefault();
jQuery("#submitf").value = 'Please wait...';
var data = {
action: 'your_function', // here php function such as your_function
data: jQuery("#ContactForm").serialize(),
};
jQuery.post(ajaxurl, data, function(response) {
......................
});
});
Any confusion comment?
for ajax use this code :
use the below code in .php file and replace $ with jQuery if it not works
$().ready(function() {
var ajaxurl = "<?php echo admin_url('admin-ajax.php'); ?>";
$.post(
ajaxurl, {
'action': 'set_the_city',
//pass all the parameter from the form in key value pairs here
},
function(output) {
console.log(output)
});
});
WordPress provides a hook for ajax call use that instead.
add_action('wp_ajax_set_the_city', 'set_the_city');
add_action('wp_ajax_nopriv_set_the_city', 'set_the_city');
function set_the_city() {
//all the data can be retrieved by $_REQUEST so do the coding for the_action_function() here.
}
My application form sends and I am able to receive all the information the user inserts. However upon integrating the below ajax script, the form fails to send all the values from the form, i.e EMAIL ADDRESS, FIRSTNAME, LASTNAME AND NOTES. In other words, I only receive the AGE, GENDER, EDUCATION AND SPECIALIZATION field values in my email.
The ajax script validates the fields and serializes the form's input and eventually sends a success message.
Please find the files:
contact.php
<form id="apply_form" method="post" action="Processor.php">
<input type="text" name="applyEmail" id="applyEmail" class="requiredField email" />
<input type="text" name="applyFirstName" id="applyFirstName" class="requiredField" />
<input type="text" name="applyLastName" id="applyLastName" class="requiredField" />
<div class="clearfix">
<select name="applyAge" id="applyAge" class="requiredField" >
<option value="age">age</option>
<option value="18-24">18 - 24</option>
<option value="25-34">25 - 34</option>
<option value="35 and over">35 and over</option>
</select>
</div>
<select name="applyGender" id="applyGender" class="requiredField" >
<option value="gender"><?php echo _("Gender"); ?>*</option>
<option value="male"><?php echo _("Male"); ?></option>
<option value="female"><?php echo _("Female"); ?></option>
</select>
<div class="clearfix">
<select name="applySpecialization" id="applySpecialization" class="requiredField" >
<option value="specialization">specialization</option>
<option value="beauty">beauty</option>
<option value="makeup">makeup></option>
<option value="studies">studies</option>
<option value="art">art</option>
<option value="theatre">theatre</option>
</select>
</div>
<div class="clearfix">
<select name="applyEducation" id="applyEducation" class="requiredField" >
<option value="education">education</option>
<option value="basic">basic</option>
<option value="high">high</option>
<option value="polytechnic">poly</option>
<option value="masters">masters</option>
</select>
</div>
<div class="clearfix">
<textarea name="applyNotes" id="applyNotes" cols="25" rows="8"></textarea>
</div>
<input type="submit" id="sendApplication" name="sendApplication" value="Apply" />
ajax.js
if ($("#apply_form")[0]) {
$('#apply_form').submit(function () {
$('#apply_form .error').remove();
$('.requiredField').removeClass('fielderror');
$('.requiredField').addClass('fieldtrue');
$('#apply_form span strong').remove();
var hasError = false;
$('#apply_form .requiredField').each(function () {
if (jQuery.trim($(this).val()) === '') {
var labelText = $(this).prev('label').text();
$(this).addClass('fielderror');
$('#apply_form span').html('<strong>*Please fill out all fields.</strong>');
hasError = true;
} else if ($(this).hasClass('email')) {
var emailReg = /^([\w-\.]+#([\w-]+\.)+[\w-]{2,4})?$/;
if (!emailReg.test(jQuery.trim($(this).val()))) {
var labelText = $(this).prev('label').text();
$(this).addClass('fielderror');
$('#apply_form span').html('<strong>Your email address is incorrect</strong>');
hasError = true;
}
}
});
if (!hasError) {
$.ajax({
url: 'applyProcess.php',
type: "POST",
data: {
"applyFirstName" : $('#applyFirstName').val(),
"applyLastName" : $('#applyLastName').val(),
"applyEmail" : $('#applyEmail').val(),
"applyAge" : $('#applyAge').val(),
"applyGender" : $('#applyGender').val(),
"applySpecialization" : $('#applySpecialization').val(),
"applyEducation" : $('#applyEducation').val(),
"applyNotes" : $('#applyNotes').val(),
"sendApplication" : true
}
}).done(function(rsp) {
$('#sendApplication').attr('disabled', 'disabled');
$('#apply_form').fadeOut(500);
$('.contact-success').fadeIn(500);
}).fail(function() {
$('#apply_form').fadeOut(500);
$('.contact-fail').fadeIn(500);
});
}
return false;
});
}
processor.php
<?php
include 'library.php'; // include the library file
include "classes/class.phpmailer.php"; // include the class name
if(isset($_POST['sendApplication'])) {
$email = $_POST['applyEmail'];
$fname = $_POST['applyFirstName'];
$lname = $_POST['applyLastName'];
$selected_val_age = $_POST['applyAge'];
$selected_val_gender = $_POST['applyGender'];
$selected_val_specialization = $_POST['applySpecialization'];
$selected_val_education = $_POST['applyEducation'];
$notes = $_POST['applyNotes'];
function clean_string($string) {
$bad = array("content-type","bcc:","to:","cc:","href");
return str_replace($bad,"",$string);
}
$email_message = "Applicant's Details.\n\n";
$email_message = "<table>";
$email_message .= "First Name: ".clean_string($fname)."\n";
$email_message .= "Surname: ".clean_string($lname)."\n";
$email_message .= "Email: ".clean_string($email)."\n";
$email_message .="Age: ".clean_string($selected_val_age)."\n";
$email_message .= "Gender: ".clean_string($selected_val_gender)."\n";
$email_message .= "Specialization: ".clean_string($selected_val_specialization)."\n";
$email_message .= "Education Level Attained: ".clean_string($selected_val_education)."\n";
$email_message .= "About Applicant: ".clean_string($notes)."\n";
$email_message .= "</table>";
$mail = new PHPMailer();
$mail->IsSMTP();
$mail->SMTPDebug = 2;
$mail->Host = SMTP_HOST;
$mail->Port = SMTP_PORT; //Port of the SMTP like to be 25, 80, 465 or 587
$mail->Username = SMTP_UNAME;
$mail->Password = SMTP_PWORD;
$mail->SMTPAuth = true;
$mail->FromName = $lname.' '.$fname;
$mail->From = $email; //From address of the mail
$mail->Subject = ("Application Form"); //Subject of your mail
$mail->AddAddress("me#me.com");
$mail->AddCC("me#you.com");
$mail->AddReplyTo("me#me.com", "Man");
//Read an HTML message body from an external file, convert referenced images to embedded, convert HTML into a basic plain-text alternative body
$mail->Body = $email_message;
$mail->AltBody = $email_message;
$send = $mail->Send(); //Send the mails
}
?>
I cant figure out why the ajax script is not processing all other values though it does everything else (even returning the success message.)
Any assistance will be highly appreciated. THANKS
You are serializing the form, the discarding the data and trying to recreate it manually. Dont do that, just send the serialized data:
var formInput = $(this).serialize();
$.ajax({
url: 'applyProcess.php',
type: "POST",
data: formInput,
...
As it turns out, i was using two identical Form ID's. everything worked accordingly after changing the forms' ID names.
I am trying to send an email from a form using php ,here is my PHP code(along with the validation ,didn't want to leave anything out :_)
<?php
/*
* Contact Form Class
*/
header('Cache-Control: no-cache, must-revalidate');
header('Expires: Mon, 26 Jul 1997 05:00:00 GMT');
header('Content-type: application/json');
$admin_email = 'sgg3590#rit.edu'; // Your Email
$message_min_length = 5; // Min Message Length
class Contact_Form{
function __construct($details, $email_admin, $message_min_length){
$this->name = stripslashes($details['name']);
$this->email = trim($details['email']);
$this->subject = 'Contact from Your Website'; // Subject
$this->message = stripslashes($details['message']);
$this->email_admin = $email_admin;
$this->message_min_length = $message_min_length;
$this->response_status = 1;
$this->response_html = '';
}
private function validateEmail(){
$regex = '/^([\w-]+(?:\.[\w-]+)*)#((?:[\w-]+\.)*\w[\w-]{0,66})\.([a-z]{2,6}(?:\.[a-z]{2})?)$/i';
if($this->email == '') {
return false;
} else {
$string = preg_replace($regex, '', $this->email);
}
return empty($string) ? true : false;
}
private function validateFields(){
if(!$this->name)
{
$this->response_html .= '<p>Please enter your name</p>';
$this->response_status = 0;
}
// Check email
if(!$this->email)
{
$this->response_html .= '<p>Please enter an e-mail address</p>';
$this->response_status = 0;
}
// Check valid email
if($this->email && !$this->validateEmail())
{
$this->response_html .= '<p>Please enter a valid e-mail address</p>';
$this->response_status = 0;
}
// Check message length
if(!$this->message || strlen($this->message) < $this->message_min_length)
{
$this->response_html .= '<p>Please enter your message. It should have at least '.$this->message_min_length.' characters</p>';
$this->response_status = 0;
}
}
private function sendEmail(){
$mail = mail($this->email_admin, $this->subject, $this->message,
"From: ".$this->name." <".$this->email.">\r\n"
."Reply-To: ".$this->email."\r\n"
."X-Mailer: PHP/" . phpversion());
if($mail)
{
$this->response_status = 1;
$this->response_html = '<p>Thank You!</p>';
}
else
{
$this->response_status = 0;
$this->response_html = '<p>Sending failed</p>';
}
}
function sendRequest(){
$this->validateFields();
if($this->response_status)
{
$this->sendEmail();
}
$response = array();
$response['status'] = $this->response_status;
$response['html'] = $this->response_html;
echo json_encode($response);
}
}
$contact_form = new Contact_Form($_POST, $admin_email, $message_min_length);
$contact_form->sendRequest();
?>
here is how I am calling it
BRUSHED.contactForm = function(){
$("#contact-submit").on('click',function() {
$contact_form = $('#contact-form');
var fields = $contact_form.serialize();
$.ajax({
type: "POST",
url: "_include/php/contact.php",
data: fields,
dataType: 'json',
success: function(response) {
if(response.status){
$('#contact-form input').val('');
$('#contact-form textarea').val('');
}
$('#response').empty().html(response.html);
}
});
return false;
});
}
And here is my form
<form id="contact-form" class="contact-form" action="#">
<p class="contact-name">
<input id="contact_name" type="text" placeholder="Full Name" value="" name="name" />
</p>
<p class="contact-email">
<input id="contact_email" type="text" placeholder="Email Address" value="" name="email" />
</p>
<p class="contact-message">
<textarea id="contact_message" placeholder="Your Message" name="message" rows="5" cols="40"></textarea>
</p>
<p class="contact-submit">
<a id="contact-submit" class="submit" href="#">Send Your Email</a>
</p>
<div id="response">
</div>
</form>
The validations work proper so its going to the php file, but I can't send the email and the response div is not fill after I push the send button(neither with thank you or sending fail)
I followed this code from a website and I Don't really understand whats wrong here.. :(
First make sure you have set your machine host same as domain name, as sometimes mail-servers will deny mail-headers that doesn't have matching domain, like Sender: test#test.org but From: localhost.
Then, install postfix so it will correct any improper / incorrect stuff in the email and lastly, you're missing email headers there. Here are my example that works for me:
<?php
try {
$to = 'user#test.org';
$subject = 'Mail Test';
$message = <<<TEXT
Mail request received
TEXT;
$message = str_replace("\n.", "\n..", $message);
$headers = 'MIME-Version: 1.0' . "\r\n";
$headers .= 'Content-type: text/html; charset=iso-8859-1' . "\r\n";
$headers .= 'From: Test Org. <webmaster#test.org>' . "\r\n" .
'Reply-To: webmaster#test.org' . "\r\n" .
'X-Mailer: PHP/' . phpversion();
mail($to, $subject, $message, $headers);
printf("Mail sent to " + $to);
} catch (Exception $e) {
printf("Error occured: " + $e);
}
?>
If it still fails, you can try sending a test message from console echo "this is the body" | mail -s "test" "receipent#test.org" and see if it works. If both failed, best to ask server vendor as maybe they have set outgoing mail disabled or something.
Well I was using local host with WAMP and realized wamp server doesn't provide the functionality . THe code is good and working though.
Thanks