Form emailing with script - php

I'm french (sorry for the english) and I'm looking for a solution to this problem.
I made a form witch send a mail to the adress I indicate in the contact.php file.
The problem is that the mail I receive does not contain the "emailSchool" variable.
Here are some of my files :
My html file :
<div id="formulaire">
<form id="myForm" action="contact.php" method="post">
<label for="emailName">Nom et prénom:</label>
<input name="emailName" type="text" id="emailName"/>
<label for="emailFrom">Email:</label>
<input name="emailFrom" type="text" id="emailFrom"/>
<label for="emailSchool">Ecole :</label>
<input name="emailSchool" type="text" id="emailSchool"/>
<label for="emailMessage">Message: (optionnel)</label>
<textarea name="emailMessage" cols="30" rows="9" id="emailMessage"></textarea>
<input style="padding-left:5px; width:80px; height:32px;" type="image" src="images/send.png" id="submit" class="submit" alt="ENVOYER"/>
<input type="hidden" name="submitted" id="submitted" value="true" />
</form>
My script :
$("#submit").click(function(){
var hasError = false;
var emailReg = /^([\w-\.]+#([\w-]+\.)+[\w-]{2,4})?$/;
var emailFromVal = $("#emailFrom").val();
if(emailFromVal == '') {
$("#emailFrom").addClass("error");
hasError = true;
} else if(!emailReg.test(emailFromVal)) {
$("#emailFrom").addClass("error");
hasError = true;
}
else
{
$("#emailFrom").removeClass("error");
}
var nameVal = $("#emailName").val();
if(nameVal == '') {
$("#emailName").addClass("error");
hasError = true;
}
else
{
$("#emailName").removeClass("error");
}
var schoolVal = $("#emailSchool").val();
if(schoolVal == '') {
$("#emailSchool").addClass("error");
hasError = true;
}
else
{
$("#emailSchool").removeClass("error");
}
var messageVal = $("#emailMessage").val();
if(messageVal == '') {
$("#emailMessage").addClass("error");
hasError = true;
}
else
{
$("#emailMessage").removeClass("error");
}
if(hasError == false) {
$(this).hide();
$("#myForm").fadeOut("fast", function(){
$("#myForm").before('<img src="images/loading.gif" alt="Loading" id="loadingImage" />');
$.post("contact.php", { emailFrom: emailFromVal, emailName: nameVal, emailSchool: schoolVal, emailMessage: messageVal },
function(data){
$("#loadingImage").fadeOut("fast", function() {
$("#loadingImage").before('<p>Votre inscription a bien été pris en compte, nous vous enverrons un email pour confirmer !</p>');
});
}
);
});
}
return false;
}
And my .php file :
<?php
$nameVal=$POST['emailName'];
$emailFromVal=$POST['emailFrom'];
$messageVal=$POST['emailMessage'];
$schoolVal=$POST['emailSchool'];
$to='mymail#gmail.com';
$sujet='Nouvel incrit JEIC CHALLENGE !'.$emailFrom;
$msg='Message :'.$emailMessage;
$mailHeader = "From = {$emailFrom}";
$mailBody = "Nom = {$emailName} Ecole = {$emailSchool}";
mail($to, $sujet, $msg, $mailBody , $mailHeader);
?>
The problem is that I don't have the "School" field in the mail I receive.
Maybe somebody have a solution ?
Thanks a lot.

You are defining:
$schoolVal=$POST['emailSchool'];
And using in your header:
$emailSchool

Maybe change {$emailSchool} into {$schoolVal} ....
You mix POST names and locals...

Related

how to validate the minlength and maxlength of textarea?

I want to validate the minlength and maxlength of textarea before submitting, can anyone tell me details?
<form id="contact-je" action="<?php echo JURI::current(); ?>" method="post">
<div class="input">
<label id="je_hide_message" for="message"><?php echo JText::_("$message"); ?></label>
<textarea name="je_message" id="message" class="requiredField" rows="4"
placeholder="<?php echo $message; ?>"><?php if (isset($_POST['je_message'])) {
if (function_exists('stripslashes')) {
echo stripslashes($_POST['je_message']);
} else {
echo $_POST['je_message'];
}
} ?></textarea>
<?php if (!isset($_SESSION)) {
if ($messageError != '') { ?><span
class="error"><?php echo $messageError; ?></span><?php }
} ?>
</div>
<div class="input">
<button name="submit" type="submit"
class="je_button"><?php echo JText::_("$submit") ?></button>
<input type="hidden" name="submitted" id="submitted" value="true"/>
</div>
</form>
<?php } ?>
</div>
If you are allowed to use the browser feature, you can just set minlength and maxlength attributes of <textarea>.
<form>
<textarea minlength="5" maxlength="10"></textarea>
<input type="submit">
</form>
I add following codes, but if enter more than 300characters, the form will still be submitted. I don't want to submit if the characters is over 300
// Validate error
$('form#contact-je').submit(function () {
$('form#contact-je .error').remove();
var hasError = false;
$('.requiredField').each(function () {
if ($.trim($(this).val()) == '') {
var labelText = $(this).prev('label').text();
$(this).parent().append('<span class="error">Pls enter ' + labelText + '!</span>');
$(this).addClass('invalid');
hasError = true;
} else if ($(this).hasClass('email')) {
var emailReg = /^([\w-\.]+#([\w-]+\.)+[\w-]{2,4})?$/;
if (!emailReg.test($.trim($(this).val()))) {
var labelText = $(this).prev('label').text();
$(this).parent().append('<span class="error">You\'ve entered an invalid ' + labelText + '!</span>');
$(this).addClass('invalid');
hasError = true;
}
}
});
//Limit message characters
$('#message').keyup(function() {
if ($(this).val().length > 300){
$(this).parent().append('<span class="error">ffffff</span>');
$(this).addClass('invalid');
hasError = true;
}
});
if (!hasError) {
var formInput = $(this).serialize();
$.post($(this).attr('action'), formInput, function (data) {
$('form#contact-je').slideUp("fast", function () {
$(this).before('<span class="success"><strong>Thank you!</strong> We have received your email.<br />We will get back to you in 12 hours.<br />-- Pneuflex China</span>');
});
});
}
return false;
});

Echo div class after form is submitted

I have a contact form on my website. When a user presses submit with their details filled it, it sends me an email. However, when they click submit, a green box should appear below <div class="sent-message"> yet, when I click submit, it shows a red box and says, "mail sent". Here are the PHP lines in contact.php that are causing this...
Simply, the box should be changed to green and have the text from sent-message instead of this.
if($mail->Send()) {
echo "mail sent";
}
else {
echo "mail sent failed";
}
<div class="form">
<form action="contact.php" method="post" role="form" class="php-email-form">
<div class="form-group">
<input type="text" name="name" class="form-control" id="name" placeholder="Your Name" data-rule="minlen:4" data-msg="Please enter at least 4 chars" />
<div class="validate"></div>
</div>
<div class="form-group">
<input type="email" class="form-control" name="email" id="email" placeholder="Your Email" data-rule="email" data-msg="Please enter a valid email" />
<div class="validate"></div>
</div>
<div class="form-group">
<input type="text" class="form-control" name="subject" id="subject" placeholder="Subject" data-rule="minlen:4" data-msg="Please enter at least 8 chars of subject" />
<div class="validate"></div>
</div>
<div class="form-group">
<textarea class="form-control" name="message" rows="5" data-rule="required" data-msg="Please write something for us" placeholder="Message"></textarea>
<div class="validate"></div>
</div>
<div class="mb-3">
<div class="loading">Loading</div>
<div class="error-message"></div>
<div class="sent-message">Your message has been sent. Thank you!</div>
</div>
<div class="text-center"><button type="submit" title="Send Message">Send Message</button></div>
</form>
</div>
Here is the jQuery:
!(function($) {
"use strict";
$('form.php-email-form').submit(function(e) {
e.preventDefault();
var f = $(this).find('.form-group'),
ferror = false,
emailExp = /^[^\s()<>#,;:\/]+#\w[\w\.-]+\.[a-z]{2,}$/i;
f.children('input').each(function() { // run all inputs
var i = $(this); // current input
var rule = i.attr('data-rule');
if (rule !== undefined) {
var ierror = false; // error flag for current input
var pos = rule.indexOf(':', 0);
if (pos >= 0) {
var exp = rule.substr(pos + 1, rule.length);
rule = rule.substr(0, pos);
} else {
rule = rule.substr(pos + 1, rule.length);
}
switch (rule) {
case 'required':
if (i.val() === '') {
ferror = ierror = true;
}
break;
case 'minlen':
if (i.val().length < parseInt(exp)) {
ferror = ierror = true;
}
break;
case 'email':
if (!emailExp.test(i.val())) {
ferror = ierror = true;
}
break;
case 'checked':
if (! i.is(':checked')) {
ferror = ierror = true;
}
break;
case 'regexp':
exp = new RegExp(exp);
if (!exp.test(i.val())) {
ferror = ierror = true;
}
break;
}
i.next('.validate').html((ierror ? (i.attr('data-msg') !== undefined ? i.attr('data-msg') : 'wrong Input') : '')).show('blind');
}
});
f.children('textarea').each(function() { // run all inputs
var i = $(this); // current input
var rule = i.attr('data-rule');
if (rule !== undefined) {
var ierror = false; // error flag for current input
var pos = rule.indexOf(':', 0);
if (pos >= 0) {
var exp = rule.substr(pos + 1, rule.length);
rule = rule.substr(0, pos);
} else {
rule = rule.substr(pos + 1, rule.length);
}
switch (rule) {
case 'required':
if (i.val() === '') {
ferror = ierror = true;
}
break;
case 'minlen':
if (i.val().length < parseInt(exp)) {
ferror = ierror = true;
}
break;
}
i.next('.validate').html((ierror ? (i.attr('data-msg') != undefined ? i.attr('data-msg') : 'wrong Input') : '')).show('blind');
}
});
if (ferror) return false;
var this_form = $(this);
var action = $(this).attr('action');
if( ! action ) {
this_form.find('.loading').slideUp();
this_form.find('.error-message').slideDown().html('The form action property is not set!');
return false;
}
this_form.find('.sent-message').slideUp();
this_form.find('.error-message').slideUp();
this_form.find('.loading').slideDown();
if ( $(this).data('recaptcha-site-key') ) {
var recaptcha_site_key = $(this).data('recaptcha-site-key');
grecaptcha.ready(function() {
grecaptcha.execute(recaptcha_site_key, {action: 'php_email_form_submit'}).then(function(token) {
php_email_form_submit(this_form,action,this_form.serialize() + '&recaptcha-response=' + token);
});
});
} else {
php_email_form_submit(this_form,action,this_form.serialize());
}
return true;
});
function php_email_form_submit(this_form, action, data) {
$.ajax({
type: "POST",
url: action,
data: data,
timeout: 40000
}).done( function(msg){
if (msg == 'OK') {
this_form.find('.loading').slideUp();
this_form.find('.sent-message').slideDown();
this_form.find("input:not(input[type=submit]), textarea").val('');
} else {
this_form.find('.loading').slideUp();
if(!msg) {
msg = 'Form submission failed and no error message returned from: ' + action + '<br>';
}
this_form.find('.error-message').slideDown().html(msg);
}
}).fail( function(data){
console.log(data);
var error_msg = "Form submission failed!<br>";
if(data.statusText || data.status) {
error_msg += 'Status:';
if(data.statusText) {
error_msg += ' ' + data.statusText;
}
if(data.status) {
error_msg += ' ' + data.status;
}
error_msg += '<br>';
}
if(data.responseText) {
error_msg += data.responseText;
}
this_form.find('.loading').slideUp();
this_form.find('.error-message').slideDown().html(error_msg);
});
}
})(jQuery);
You could do something like this, in contact.php:
$sent = false;
if($mail->Send()) { $sent = true; }
Then in your html you show message:
<?php
if($sent) { ?>
<div class="sent-message">Your message has been sent. Thank you!</div>
<?php } ?>
UPDATE
So your form submission is controlled by jQuery. You can show message by just echo 'OK' instead of "mail sent" in your php script
if($mail->Send()) {
echo "mail sent";
$color = 'green';
}
else {
echo "mail sent failed";
$color = 'red';
}
?>
<div class="mb-3">
<div class="loading">Loading</div>
<div class="error-message"></div>
<div class="sent-message" style='background-color:"<?php echo $color;' ?>">Your message has been sent. Thank you!</div>
</div>
Your code must return
if($mail->Send()) {
echo "OK";
}
and if you want differen message, you can change it here:
<div class="sent-message">My new message</div>

Empty page after form submit (PHP & Javascript)

I have a form script that sends an email after its been submitted. A javascript removes the form after its been submitted.
But when I submit my form it shows me the empty .php file.
Heres my index.html code:
<!--Here is container with email subscription-->
<div class="container-fluid yellow-container bg-mail">
<div class="row-fluid">
<div class="span12">
<h2>Laat hier je email adres achter, zodat wij weten dat je van de partij bent</h2>
<p>Deze uitnodiging geldt voor jou en een relatie!</p>
<form action="save.php" id="subscribe-form" method="post" name="subscribe-form">
<input type="email" name="email" placeholder="Hier je emailadres" id="email" class="email required">
<button class="btn btn-inverse" id="submit" type="submit" value="Subscribe">Count me in!</button>
</form>
</div>
</div>
</div>
save.php code:
<?php
if (isset($_POST['email'])) {
//Email information
$admin_email = "marco#daretodesign.nl";
$email = $_POST['email'];
//send email
mail($admin_email, "Inschrijving via Dukdalf", $email . " " . "heeft zich ingeschreven via de website", "Van:" . $email);
}
?>
javascript code:
//Subscribe Form
if($('#subscribe-form').length && jQuery()) {
$('form#subscribe-form').submit(function() {
$('form#subscribe-form .error').remove();
var hasError = false;
$('.required').each(function() {
if(jQuery.trim($(this).val()) === '') {
var labelText = $(this).prev('label').text();
$(this).parent().append('<div class="error">Vul a.u.b. uw email in.'+labelText+'</div>');
$(this).addClass('inputError');
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).parent().append('<div class="error">Vul a.u.b. een geldig email in.'+labelText+'</div>');
$(this).addClass('inputError');
hasError = true;
}
}
});
if(!hasError) {
$('form#subscribe-form input.submit').fadeOut('normal', function() {
$(this).parent().append('');
});
var formInput = $(this).serialize();
$.post($(this).attr('action'),formInput, function(data){
$('form#subscribe-form').slideUp("fast", function() {
$(this).before('<div class="error">Bedankt voor het inschrijven!</div>');
});
});
}
return false;
});
Thanks for help in advance :)
it shows you your blank php page because you after send email should redirect user to somewhere, perhaps with:
header('Location: http://www.example.com/');
exit;
Regards,
Marcelo

HTML form with 2 (hidden) submit buttons and 1 other hidden input

I'm trying to build this application that runs on Android tablets with barcode scanners attached.
The barcode scanners send an Enter after each scanned code.
I need to scan 2 barcodes and submit the form.
I created a form with two sets of input + submit button, the second one hidden. After the first barcode is scanned and the scnner send the Enter key, the hidden elements are revealed and I can scan the second barcode. However, the second time the Enter key doesn't work. It only work if I push the button (after I unhide it).
How can I take care of this so it will not need user input (other than scanning barcodes)?
Here's my code so far:
<form action="barcode.php" method="post" class="pure-form" style="width:100%">
<fieldset>
<legend>Scaneaza o fisa noua de <?php echo $operation; ?>:</legend>
<input type="text" name="barcode" autofocus id="InputID" placeholder="Codul de bare" style="width:100%;font-size:2em">
<button style="width:0;visibility:hidden;" type="submit" onclick="show_popup('my_popup'); return false;"></button>
<div id="my_popup" style="display:none;border:3px dotted gray;padding:.3em;background-color:white;position:absolute;width:80%;height:20%;margin:-50px 50px 0 50px;">
<legend>Introdu numarul de KO-uri:</legend>
<input type="text" name="kos" autofocus id="InputID" placeholder="KO-uri" style="width:100%;font-size:2em">
<button type="submit" class="pure-button pure-button-primary" style="/*width:0;visibility:hidden;*/" onclick="hide_popup('my_popup'); return true;">Trimite</button>
</div>
</fieldset>
</form>
<script type="text/javascript">
function FocusOnInput() { document.getElementById("InputID").focus(); }
function show_popup(id) {
if (document.getElementById){
obj = document.getElementById(id);
if (obj.style.display == "none") {
obj.style.display = "";
}
}
}
function hide_popup(id){
if (document.getElementById){
obj = document.getElementById(id);
if (obj.style.display == ""){
obj.style.display = "none";
}
}
}
</script>
And the barcode.php file:
<?php
ob_start();
mysql_connect ("localhost","root","root") or die (mysql_error());
mysql_select_db ("eficacitate");
$barcode = $_POST["barcode"];
$kos = $_POST["kos"];
$marca = $_COOKIE["marca"];
$operation = $_COOKIE["operation"];
if (substr($barcode,0,1)=="^") {
$j_nou = substr($barcode,1,strpos($barcode, "|")-1);
$parts = explode('|',$barcode);
$of_nou = $parts[1];
$cantitate_nou = $parts[2];
$serie_nou = $parts[3];
$adauga="INSERT INTO master (marca, operation,j,of,cantitate,serie,kos)
VALUES
('$marca','$operation','$j_nou','$of_nou','$cantitate_nou','$serie_nou','$kos')";
mysql_query($adauga);
}
header('Location: /eficacitate/scan.php');
ob_flush();
?>
Please give this a try:
<form action="barcode.php" method="post" class="pure-form" style="width:100%">
<fieldset>
<legend>Scaneaza o fisa noua de <?php echo $operation; ?>:</legend>
<input type="text" name="barcode" autofocus id="InputID" placeholder="Codul de bare" style="width:100%;font-size:2em">
<button id='barcodeButton' style="width:0;visibility:hidden;" type="submit" onclick="show_popup('my_popup'); return false;"></button>
<div id="my_popup" style="display:none;border:3px dotted gray;padding:.3em;background-color:white;position:absolute;width:80%;height:20%;margin:-50px 50px 0 50px;">
<legend>Introdu numarul de KO-uri:</legend>
<input type="text" name="kos" autofocus id="InputID" placeholder="KO-uri" style="width:100%;font-size:2em">
<button id='kosButton' type="submit" class="pure-button pure-button-primary" style="/*width:0;visibility:hidden;*/" onclick="hide_popup('my_popup'); return true;">Trimite</button>
</div>
<script type="text/javascript">
function FocusOnInput() { document.getElementById("InputID").focus(); }
document.onkeydown = function(event) {
if (event.keyCode == '13') {
barcodeButton = document.getElementById('barcodeButton');
kosButton = document.getElementById('kosButton');
if (document.getElementById('my_popup').style.display == 'none') {
barcodeButton.click();
show_popup('my_popup');
} else {
kosButton.click();
hide_popup('my_popup');
}
}
}
function show_popup(id) {
if (document.getElementById){
obj = document.getElementById(id);
if (obj.style.display == "none") {
obj.style.display = "";
}
}
}
function hide_popup(id){
if (document.getElementById){
obj = document.getElementById(id);
if (obj.style.display == ""){
obj.style.display = "none";
}
}
}
Let me know if this solves what you are trying to achive. Just out of curiosity, why aren't you using jQuery here?

How to add AJAX Submit to PHP validation and return message?

I've been working my way up on validating a form and got the JS and PHP validation to work but I am still having a hard time adding ajax(with or without JQUERY) to submit to the php file and return a success message.
My form with CSS and JS validation:
<html>
<head>
<style type="text/css">
#nameerror {
color:red;
}
#emailerror{
color:red;
}
</style>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.0/jquery.min.js"></script>
<script type="text/javascript">
function Validate() {
var email = document.forms['form']['email'].value;
var atpos = email.indexOf('#');
var dotpos = email.lastIndexOf('.');
var name = document.forms['form']['name'].value;
if (name == null || name == ""){
document.getElementById('nameerror').innerHTML="Please enter your name";
return false;
} else if (atpos < 1 || dotpos < atpos+2 || dotpos+2 >= email.length) {
document.getElementById('emailerror').innerHTML="Please enter a valid email";
return false;
} else {
}
}
</script>
</head>
<body>
<div>Sign Up</div>
<form name="form" action="form_validation.php" id="form" onsubmit="return Validate();" method = 'post'>
<label>Name:</label><br/>
<input id='name' type="text" name='name' /><br/>
<span id="nameerror"></span><br/>
<label>Email:</label><br/>
<input type='text' name='email' id = 'email'/> <br/>
<span id= "emailerror"></span><br/>
<label>Comments:</label><br/>
<textarea name='comments' id ='comments'></textarea><br/>
<span id="comerror"></span>
<input type="submit" name="submit" value="Submit"/>
<span id="success" style="display:none">Your message has been sent successfully.</span>
</form>
</body>
</html>
And this is form_validation.php:
<?php
if(isset($_POST['submit'])){
if($_POST['name']){
$name = $_POST['name'];
}
if(!preg_match('/^[a-zA-Z\s]+$/', $name)){
echo "Name can only contain letters.";
return false;
} else {
echo "Name accepted";
}
if($_POST['email']){
$email = $_POST['email'];
}
$pattern = '/^[_a-z0-9-]+(\.[_a-z0-9-]+)*#[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,3})$/';
if(!preg_match($pattern, $email)){
echo "Please enter a valid email address.";
return false;
} else {
echo "Email Valid";
}
if($_POST['comments']){
$comments = $_POST['comments'];
}
if (strlen($comments) > 100){
echo "please enter less than 100 characters.";
return false;
}
}
?>
thanks for the help!
$('form').on('submit',function() {
$.ajax({
url: 'form_validation.php',
data: $(this).serialize(),
type: 'POST'
}).done(function(data){
// you can append a success message to your document here
});
});

Categories