single submit button to do three functions - javascript

have been a while since i posted last thanks, in advance for all your help in the past..i have a single email box with a submit button.
What i want to do is to check this email address to make sure its not empty, if it is to display a message and then ask user to enter the valid email address which i want to validate so that it is only hotmail and gmail accounts e.g. xyz#hotmail.com and xyz#gmail.com and nothing else..
my code below works ok to check for empty and does display alert message on screen but i do not know how to manpulate the email address check and if all is ok how to use the same one submit button to submit the valid email with thank u popup message after submissions..thanks in advance...singhy
ps: apologises in advance for any beginners mistake i have made ...sorry
<?php
if(isset($_POST['email'])) {
$to = 'xyz#hotmail.com';
$subject = '';
$email = $_POST['email_from'];
//$message = "LIST \r\n".
$message = "signoff list name \r\n";
}
$email_from = $_POST['email'];
// create email headers
$message = wordwrap($message, 100, "\r\n");
$headers = 'From: '.$email."\r\n".
'Reply-To: '.$email."\r\n" .
'X-Mailer: PHP/' . phpversion();
#mail($to, $subject, $message, $headers);
?>
<p>If you would like to receive our weekly newsletter email address below.</p>
<script type="text/javascript">
function IsEmpty(){
if(document.forms['isgtest'].email_from.value == "")
{
alert("Email field is empty, please enter email format");
return false;
}
//return submit "email_from.value";
(document.forms['test'].email_from.value == "subscribe")
//return .email_from.value == "";
//alert("thank u for joining the list !");
//return true;
}
</script>
<!--<script type="text/javascript"></script>-->
<form name="isgtest" class="rform" method="post" action="g.php">
<fieldset><legend>testing...</legend>
<label for="email_from"><span style="color: #ff0000;"><strong>*</strong>
</span>Email address:<input id="email_from" type="text" name="email_from" size="25" /> <input id="insert" id="btn" onclick="return IsEmpty();" style="float: right;" type="button" name="submit" value="Subscribe" /></fieldset>
</form>

If you are going for frontend validation (which should only be used to improve the user experience, never trust user input and always validate at the server side!), why not use the HTML5 features that exist for exactly that purpose. Something like this:
<form>
<label>Email:
<input type='email' pattern=".+(#gmail.com|#hotmail.com)" required />
</label>
<button type="submit">subscribe</button>
</form>
type=email makes sure only email addresses are accepted
required makes sure a value is provided before it can be submitted
pattern accepts a regex to which the input needs to comply before it can be submitted.
Personally I'm not a big fan of the default error messages my browser produces, but I'm even less of a fan of the alerts you are using, so...
If you insist on going the javascript way, I would advise something like this (pseudo code, untested):
function isEmpty(input) { ... }
function isEmail(input) { ... }
function isGmailOrHotmail(input) { ... }
function isValid(node) {
var value = node.value;
return ! isEmpty(value) && isEmail(value) && isGmailOrHotmail(value);
}
And then you could bind the isValid function to your submit button (preferably from your script file or block, but the inline onclick way should work as well)

<?php
$email_from = $_POST['email'];
$errors=array(); //track the errors as the script runs
function isValidEmail($addr) // Check for a valid email
{
return filter_var($addr, FILTER_VALIDATE_EMAIL) ? TRUE : FALSE;
}
if(!isValidEmail($email_from))$errors[]='Please enter a valid email address';
//Next, test for the email provider you wanted to filter by
$atPos=strpos($email_from,'#');//find the # symbol
$afterAt=substr($email_from,$atPos,strlen($email_from)-$atPos); //get everything after
$dotPos=strpos($afterAt,'.');
$domain=strtolower(substr($afterAt,0,$dotPos)); //get the typed domain, lowercase
if($domain!='hotmail'||$domain!='gmail')$errors[]='Email must be hotmail or gmail';
if(isset($_POST['email'])) {
if(count($errors)<0)
{
$to = 'xyz#hotmail.com';
$subject = '';
$email = $_POST['email_from'];
//$message = "LIST \r\n".
$message = "signoff list name \r\n";
// create email headers
$message = wordwrap($message, 100, "\r\n");
$headers = 'From: '.$email."\r\n".
'Reply-To: '.$email."\r\n" .
'X-Mailer: PHP/' . phpversion();
#mail($to, $subject, $message, $headers);
}
}// note that I changed the nesting to only trigger the mail on post
?>
<p>If you would like to receive our weekly newsletter email address below.</p>
<script type="text/javascript">
function IsEmpty(){
if(document.forms['isgtest'].email_from.value == "")
{
alert("Email field is empty, please enter email format");
return false;
}
//return submit "email_from.value";
(document.forms['test'].email_from.value == "subscribe")
//return .email_from.value == "";
//alert("thank u for joining the list !");
//return true;
}
</script>
<!--<script type="text/javascript"></script>-->
<?php
if(count($errors)>0)
{
foreach $errors as $e //Now tell the user what went wrong
{
echo "$e<br>"; // you can also use '' to enclose js tags and use alert
}
}
?>
<form name="isgtest" class="rform" method="post" action="g.php">
<fieldset><legend>testing...</legend>
<label for="email_from"><span style="color: #ff0000;"><strong>*</strong>
</span>Email address:<input id="email_from" type="text" name="email_from" size="25" /><input id="insert" id="btn" onclick="return IsEmpty();" style="float: right;" type="button" name="submit" value="Subscribe" /> </fieldset>
</form>

Related

HTML Form won't send email on submit

I've developed an iOS app and rails backend server. While I took some HTML classes back in university, it's been a long while since I've touched any.
I purchased a 'template' website to be my application landing page. I've tweaked it to be what I want, but I'm having 1 issue with the Contact/Form Submission page. When I press send, I do not receive an email at the intended email address. I'm not sure if this is an issue with the code (I'm guessing not, I would think this highly rated template would have had something like this correct), or if I need to set up something with my domain that I currently haven't done as I wouldn't know about it.
Here's the relevant code...
index.html
<form action="javascript:;" method="post">
...
<input type="submit" class="button white" value="Send →" />
</form>
send_email.php
<?php
// Replace this with your own email address
$to="example#gmail.com";
// Extract form contents
$name = $_POST['name'];
$email = $_POST['email'];
$website = $_POST['website'];
$subject = $_POST['subject'];
$message = $_POST['message'];
// Validate email address
function valid_email($str) {
return ( ! preg_match("/^([a-z0-9\+_\-]+)(\.[a-z0-9\+_\-]+)*#([a-z0-9\-]+\.)+[a-z]{2,6}$/ix", $str)) ? FALSE : TRUE;
}
// Return errors if present
$errors = "";
if($name =='') { $errors .= "name,"; }
if(valid_email($email)==FALSE) { $errors .= "email,"; }
if($message =='') { $errors .= "message,"; }
// Send email
if($errors =='') {
$headers = 'From: FluidApp <no-reply#fluidapp.com>'. "\r\n" .
'Reply-To: '.$email.'' . "\r\n" .
'X-Mailer: PHP/' . phpversion();
$email_subject = "Website Contact Form: $email";
$message="Name: $name \n\nEmail: $email \n\nWebsite: $website \n\nSubject: $subject \n\nMessage:\n\n $message";
mail($to, $email_subject, $message, $headers);
echo "true";
} else {
echo $errors;
}
?>
However, nothing is being sent to my email "example#gmail.com".
What might I be missing here?
Maybe replace
<form action="javascript:;" method="post">
with
<form action="send_email.php" method="post">
That should do it, assuming the ... in your HTML snippet contains the right variables for the form submission- name, email, website, subject, message, etc.
EDIT: OP figured it out.
Place the <form action="send_email.php" method="post">
and remove <form action="javascript:;" method="post">
it will work perfect your send_email.php is good
place all 2 files in same folder

showing text in div without reloading the page

In the following code, I have a contact form and in that form there is an email validation script. As a result of validation, I want the error message to be shown in a div called confirmation without reloading the page. Also, if the email is valid, the mail will be sent and I want the Thank you message to be shown in the same div confirmation. The problem is what can I do to prevent reloading the page and let the error message or the thanks message shows in the confirmation div?
<html>
<body>
<?php
function spamcheck($field) {
// Sanitize e-mail address
$field=filter_var($field, FILTER_SANITIZE_EMAIL);
// Validate e-mail address
if(filter_var($field, FILTER_VALIDATE_EMAIL)) {
return TRUE;
} else {
return FALSE;
}
}
?>
<?php
if (!isset($_POST["submit"])) {
?>
<form method="post" action="<?php echo $_SERVER["PHP_SELF"];?>">
From: <input type="text" name="from"><br>
Subject: <input type="text" name="subject"><br>
Message: <textarea rows="10" cols="40" name="message"></textarea><br>
<input type="submit" name="submit" value="Submit Feedback"><br>
<div id="confirmation" style="display:none" align="center"></div>
</form>
<?php
} else { // the user has submitted the form
// Check if the "from" input field is filled out
if (isset($_POST["from"])) {
// Check if "from" email address is valid
$mailcheck = spamcheck($_POST["from"]);
if ($mailcheck==FALSE) {
echo"
<script>
document.getElementById('confirmation').text ='invalid email';
</script>";
} else {
$from = $_POST["from"]; // sender
$subject = $_POST["subject"];
$message = $_POST["message"];
// message lines should not exceed 70 characters (PHP rule), so wrap it
$message = wordwrap($message, 70);
// send mail
mail("nawe11#gmail.com",$subject,$message,"From: $from\n");
echo"
<script>
document.getElementById('confirmation').text ='Thank you';
</script>";
}
}
}
?>
</body>
</html>
Thanks
<input type="text" name="from" id ="from">
Call example:
var request = $.ajax({
url: "file.php",
type: "POST",
data: { email : $('#from').val() }
});
request.done(function( msg ) {
//handle HTML
});
request.fail(function( jqXHR, textStatus ) {
//Handle problem at server side
});
PHP Side
<?php
$email = $_POST["email"]
function spamcheck($field) {
// Sanitize e-mail address
$field=filter_var($field, FILTER_SANITIZE_EMAIL);
// Validate e-mail address
if(filter_var($field, FILTER_VALIDATE_EMAIL)) {
return 'valid';
} else {
return 'no_valid';
}
}
echo spamcheck($email);
There's no way you could do that with just PHP.
What you're looking at is commonly known as AJAX, and uses client-side language (Javascript)
It's very common, and widely used on the internet. You can find many examples and production-ready scripts by searching ajax on google.
More informations here : http://www.w3schools.com/ajax/

Pop up form does not send email

I have problem with pop up form . It doesn't send email. Here is html form:
<form action="#" method="post" id="form" >
<img src="images/3.png" id="close"/>
<h2>Contact Us</h2><hr/>
<input type="text" name="name" id="name" placeholder="Name"/>
<input type="text" name="email" id="email" placeholder="Email"/>
<textarea name="message" placeholder="Message" id="msg"></textarea>
<a id="submit" href="javascript: check_empty()">Send</a>
</form>
JS to pop up html form:
function check_empty(){
if(document.getElementById('name').value == ""
|| document.getElementById('email').value == ""
||document.getElementById('msg').value == "" ){
alert ("Fill All Fields !");
}
else {
document.getElementById('form').submit();
alert ("Form submitted successfully...");
}
}
//function to display Popup
function div_show(){
document.getElementById('abc').style.display = "block";
}
//function to check target element
function check(e){
var target = (e && e.target) || (event && event.srcElement);
var obj = document.getElementById('abc');
var obj2 = document.getElementById('popup');
checkParent(target)?obj.style.display='none':null;
target==obj2?obj.style.display='block':null;
}
//function to check parent node and return result accordingly
function checkParent(t){
while(t.parentNode){
if(t==document.getElementById('abc'))
{
return false
}
else if(t==document.getElementById('close'))
{
return true
}
t=t.parentNode
}
return true
}
And php function to send form data to email. Everything work but i don't receive email on gmail. Similar php script i used to post email without pop up and it worked.
<?php
if(isset($_POST['submit'])){
$to = "myemail#gmail.com";
$from = $_POST['email'];
$first_name = $_POST['name'];
$message = $first_name . " wrote following:" . "\n\n" . $_POST['message'];
mail($to,$from,$message);
}
?>
Simple: You don't have an element named "submit" in your form, so your if() test always fails.
id != name in HTML forms; meaning, id does not equal name.
A simple work around:
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
... form was submitted ...
}
But this code is bad in any case. You should NEVER use only client-side validation. It's too easy to bypass. ALWAYS validate/verify on the server as well.
You should set your action in the form to the URL of your action in the server.

Check the security of form.

My account was suspended because of SPAM several times and my host provider told me to check my website security. May be my forms are not secured enough. Do you think that this form can be used to send spam?
Here is my code:
<script type="text/javascript">
$(document).ready(function () {
$('#form').ajaxForm({
beforeSubmit: validate
});
function validate(formData, jqForm, options) {
var name = $('input[name=name]').fieldValue();
var email = $('input[name=email]').fieldValue();
var company = $('input[name=company]').fieldValue();
var location = $('input[name=location]').fieldValue();
var phone = $('input[name=phone]').fieldValue();
var message = $('textarea[name=message]').fieldValue();
if (!name[0]) {
alert('Please enter your name');
return false;
}
if (!company[0]) {
alert('Please enter the name of your organization');
return false;
}
if (!email[0]) {
alert('Please enter your e-mail address');
return false;
}
if (!phone[0]) {
alert('Please enter your phone number');
return false;
}
if (!location[0]) {
alert('Please enter your location');
return false;
}
if (!message[0]) {
alert('Please enter your message');
return false;
}
else {
$("#form").fadeOut(1000, function () {
$(this).html("<img src='note.png' style='position: relative;margin: 0 auto;width: 500px;left: 20px;top: 30px;'/>").fadeIn(2000);
});
var message = $('textarea[name=message]').val('');
var name = $('input[name=name]').val('');
var email = $('input[name=email]').val('');
var phone = $('input[name=phone]').val('');
var company = $('input[name=company]').val('');
var location = $('input[name=location]').val('');
}
}
});
</script>
html:
<form id="form" method="post" name="form" action="send.php">
<input id="name" type="text" name="name"/>
<input id="company" type="text" name="company"/>
<input id="email" type="text" name="email"/>
<input id="phone" type="text" name="phone"/>
<input id="location" type="text" name="location"/>
<textarea name="message" id="message" rows="10"></textarea>
<input class="submit" type="submit" value="send" name="submit"></input>
</form>
php:
<?php
if($_POST){
$email = $_POST['email'];
$name = $_POST ['name'];
$company = $_POST ['company'];
$phone = $_POST ['phone'];
$location = $_POST ['location'];
$message = $_POST ['message'];
// response hash
$ajaxresponse = array('type'=>'', 'message'=>'');
try {
// do some sort of data validations, very simple example below
$all_fields = array('name', 'email', 'message');
filter_var($email, FILTER_VALIDATE_EMAIL);
foreach($all_fields as $field){
if(empty($_POST[$field])){
throw new Exception('Required field "'.ucfirst($field).'" missing input.');
}
}
// ok, if field validations are ok
// now Send Email, ect.
// let's assume everything is ok, setup successful response
$subject = "Someone has contacted you";
//get todays date
$todayis = date("l, F j, Y, g:i a") ;
$message = " $todayis \n
Attention: \n\n
Please see the message below: \n\n
Email Address: $email \n\n
Organization: $company \n\n
Phone: $phone \n\n
Location: $location \n\n
Name: $name \n\n
Message: $message \n\n
";
$from = "From: $email\r\n";
//put your email address here
mail("...#yahoo.com", $subject, $message, $from);
//prep json response
$ajaxresponse['type'] = 'success';
$ajaxresponse['message'] = 'Thank You! Will be in touch soon';
} catch(Exception $e){
$ajaxresponse['type'] = 'error';
$ajaxresponse['message'] = $e->getMessage();
}
// now we are ready to turn this hash into JSON
print json_encode($ajaxresponse);
exit;
}
?>
Many thanks!
Your form would actually be not safe against bots, because you dont got any captcha or something.
2 Options for you:
Captcha
Captcha -> you got something to fill in -> you probably know this!:)
https://www.google.com/recaptcha
Honeypot
Honeypot means, you are adding hidden fields in your form. And if those hidden fields have changed - you know that a BOT has entered content in your form. Aswell, this is better than Captchas, because your User doesnt has to fill in a Captcha
I would prefer Honeypot, because I don't like forms, where i have to fill in a Captcha once or even twice, when I failed or the captcha wasnt readable.
http://haacked.com/archive/2007/09/11/honeypot-captcha.aspx/
I have a simple approach to stopping spammers which is 100% effective, at least in my experience, and avoids the use of reCAPTCHA and similar approaches. I went from close to 100 spams per day on one of my sites' html forms to zero for the last 5 years once I implemented this approach.
another option is what I did is to use a hide field and put the time stamp on it and then compare to the time stamp on the PHP side, if it was faster than 15 seconds (depends on how big or small is your forms) that was a bot...
Taking clue from the suggestions above, I am just putting a ready code for you to use.
HTML
<form id="form" method="post" name="form" action="send.php">
<input id="name" type="text" name="name"/>
<input id="company" type="text" name="company"/>
<input id="email" type="text" name="email"/>
<input id="checkbot" type="hidden" name="timestamp" value="" />
<input id="phone" type="text" name="phone"/>
<input id="location" type="text" name="location"/>
<textarea name="message" id="message" rows="10"></textarea>
<input class="submit" type="submit" value="send" name="submit"></input>
</form>
Javascript
<script type="text/javascript">
$(document).ready(function () {
/*Set current time on the hidden field.*/
$('#checkbot').val($.now());
$('#form').ajaxForm({
beforeSubmit: validate
});
function validate(formData, jqForm, options) {
var name = $('input[name=name]').fieldValue();
var email = $('input[name=email]').fieldValue();
var company = $('input[name=company]').fieldValue();
var location = $('input[name=location]').fieldValue();
var phone = $('input[name=phone]').fieldValue();
var message = $('textarea[name=message]').fieldValue();
if (!name[0]) {
alert('Please enter your name');
return false;
}
if (!company[0]) {
alert('Please enter the name of your organization');
return false;
}
if (!email[0]) {
alert('Please enter your e-mail address');
return false;
}
if (!phone[0]) {
alert('Please enter your phone number');
return false;
}
if (!location[0]) {
alert('Please enter your location');
return false;
}
if (!message[0]) {
alert('Please enter your message');
return false;
}
else {
$("#form").fadeOut(1000, function () {
$(this).html("<img src='note.png' style='position: relative;margin: 0 auto;width: 500px;left: 20px;top: 30px;'/>").fadeIn(2000);
});
var message = $('textarea[name=message]').val('');
var name = $('input[name=name]').val('');
var email = $('input[name=email]').val('');
var phone = $('input[name=phone]').val('');
var company = $('input[name=company]').val('');
var location = $('input[name=location]').val('');
}
}
});
</script>
PHP
<?php
if($_POST){
$email = $_POST['email'];
$name = $_POST ['name'];
$company = $_POST ['company'];
$phone = $_POST ['phone'];
$location = $_POST ['location'];
$message = $_POST ['message'];
$checkbot = $_POST['timestamp'];
$time_diff = time() - $checkbot;
//If Time difference is less than 15 sec it's a bot
if($time_diff < 15){
exit;
}
// response hash
$ajaxresponse = array('type'=>'', 'message'=>'');
try {
// do some sort of data validations, very simple example below
$all_fields = array('name', 'email', 'message');
filter_var($email, FILTER_VALIDATE_EMAIL);
foreach($all_fields as $field){
if(empty($_POST[$field])){
throw new Exception('Required field "'.ucfirst($field).'" missing input.');
}
}
// ok, if field validations are ok
// now Send Email, ect.
// let's assume everything is ok, setup successful response
$subject = "Someone has contacted you";
//get todays date
$todayis = date("l, F j, Y, g:i a") ;
$message = " $todayis \n
Attention: \n\n
Please see the message below: \n\n
Email Address: $email \n\n
Organization: $company \n\n
Phone: $phone \n\n
Location: $location \n\n
Name: $name \n\n
Message: $message \n\n
";
$from = "From: $email\r\n";
//put your email address here
mail("...#yahoo.com", $subject, $message, $from);
//prep json response
$ajaxresponse['type'] = 'success';
$ajaxresponse['message'] = 'Thank You! Will be in touch soon';
} catch(Exception $e){
$ajaxresponse['type'] = 'error';
$ajaxresponse['message'] = $e->getMessage();
}
// now we are ready to turn this hash into JSON
print json_encode($ajaxresponse);
exit;
}
?>
In theory it can be used to send spam, because there are only checks if fields have values and as long the fields have a value, it does not care whether the input was human or a bot. You could improve the security by adding captcha codes (http://www.captcha.net/), to validate if an individual filling in your form is a human.
Try using this Spam Checker.
Useful program written in Java which looks up for spam IP Addresses using DNS lookups. Hope so it helps.

Organizing variables on mailto form submit

I'm using mailto on a form to open the default email service and create an email. However, all the fields on the form look horrible when they appear on the email. I have three fields noun1, verb, noun2 and when they're submitted, on the body of the email it shows up as, for example
noun1= I
verb= ate
noun2= food
Is there some way to specify how to organize/display these variables on the email body when submit is clicked so that it is formatted on the email body as
I ate food
?
The form, by request:
<form id= "formx" method="post" action="mailto:email#email.com" enctype="text/plain">
<p><label for="id_noun1">noun1:</label>
<input id="id_noun1" type="text" name="noun1"/></p>
<p><label for="id_verb">Verb:</label>
<input id="id_verb" type="text" name="verb" /></p>
<p><label for="id_noun2">noun2:</label>
<input id="id_noun2" type="text" name="noun2"/></p>
<input type="submit" value="Submit" />
Well, thanks for the help everybody, I guess.
What I settled on was taking the input from the form, creating a new element via javascript, making a link and adjusting the href on the fly. Finally, I have a javascript click event that opens an email with the information formatted as I want.
var a= document.getElementById('a');
var b= document.getElementById('b');
var c= document.getElementById('c');
var link = document.createElement('a');
link.setAttribute('href', 'mailto:me.com'
+ '?subject= Subject' + '&body='+ 'I am a ' + a.value + ', I like to ' + b.value
+ ', I also like doing ' + c.value
);
link.click();
first of all i have to say email by just html or javascript will end up looking weird just use php instead it is also quiet easy:
/first make the variables of all the things you need
$naam = $_POST['vnaam'];
$mail = $_POST['email'];
$achternaam = $_POST['anaam'];
$tel = $_POST['telefoon'];
$message = $_POST['commentaar'];
$Name = $naam; //senders name
$email = $mail; //senders e-mail adress
$recipient = "receivers email"; //recipient
$mail_body = //add the variables and text here by using . u get the same as + in javascript ;
//mail body
$subject = "Contact formulier van: " . $naam . " " . $achternaam; //subject
$header = "From: ". $Name . " <" . $email . ">\r\n"; //optional headerfields
if ($_POST) {
mail($recipient, $subject, $mail_body, $header); //mail command
exit;
}
now the if statement is the most important part. it is the part where the mail function is requested from. the pros of php is that the receiver doesnt get an email with something like:
idname=Dave
or idcheckbox=true or false (weither or not he box is checked)

Categories

Resources