I have a simple POST script for PHP which sends an email, but when I click the submit button it executes and then goes to the script directory (ex: localhost/sendMail/test.php). Is it possible to post an alert box, and then stay on the page instead of going to the script and then redirecting back onto the submit page?
This is my script.
<?php
$subject = 'Your website: Contact'; // Subject of your email
$to = 'myemail'; // Enter recipient's E-mail address
$emailTo = $_REQUEST['email'];
$headers = "MIME-Version: 1.1";
$headers .= "Content-type: text/html; charset=iso-8859-1";
$headers .= "From: " . $emailTo . "\r\n"; // Sender's E-mail
$headers .= "Return-Path:". $emailTo;
$body = 'You have received a new inquiry!' . "\n\n";
$body .= 'Name: ' . $_REQUEST['name'] . "\n";
$body .= 'Email: ' . $_REQUEST['email'] . "\n";
$body .= 'Phone: ' . $_REQUEST['phone'] . "\n\n";
$body .= 'Message: ' . $_REQUEST['message'];
if($_REQUEST['name'] != "" && $_REQUEST['email'] != "" && $_REQUEST['phone'] != "" && $_REQUEST['message'] != "")
{
if (#mail($to, $subject, $body, $headers))
{
// Transfer the value 'sent' to ajax function for showing success message.
echo 'sents';
}
else
{
// Transfer the value 'failed' to ajax function for showing error message.
echo 'failed';
}
}
else
{
$message = "Invalid fields!";
echo "<script type='text/javascript'>alert('$message');</script>";
//header("Location: http://localhost/abtek/contact.html");
exit;
}
?>
So when the alert is executed, is it possible to stop it from going to the script, and instead staying on the page until the fields are all valid to submit? As well as when they are submitted to display an alert again and stay on the page instead of doing a bunch of redirects.
Any help would be greatly appreciated.
You can submit the form with ajax/jquery and stop the redirect. See here: Stackoverflow
You can use jQuery, like this:
$('#my-submit').on('click', function(e){
e.preventDefault(); // prevents regular form submission
$.ajax({
url: 'localhost/sendMail/test.php',
data: $('form').serialize(),
success: function(result){
alert('Message: ' + result );
},
error: function(err){
alert(err)
}
})
});
In your PHP you should just do echo $message; to handle error better.
Read all you can about jQuery/AJAX, as there are important options you can explode, like using JSON.
Related
I'm trying to set up a small personal page based on kite. It comes along with a sleak contact form.
However, I was not able to get this contact form to work. After many hours, I managed to get it to send emails, but now it doesn't return a proper 'success' status, so the contact form gets updated. Instead, the echo 'success' in the called php gets printed on screen. The eMail, however, is being sent.
Any ideas what I am doing wrong?
HTML
<form id="contact-form" action="email.php" method="post" class="clearfix">
<div class="contact-box-hide">
//in here is the contact-box form
</div><!-- /.contact-box-hide -->
<div id="contact-message" class="contact-message"></div>
//This is the div, in which the success message should be posted
</form><!-- /#contact-form -->
AJAX Call
$.ajax({
type: "POST",
url: "email.php", //if I use this line, the mail is not being sent, but the email.php script hands over a proper success message to the ajax call
url: $(form).attr('action'), //if I use this line, the mail will be sent, but the email.php script prints its echo on a blank page
data: data_string,
//success
success: function(data) {
$('.contact-box-hide').slideUp();
$('.contact-message').html('<i class="fa fa-check contact-success"></i><div>Super, die Nachricht ist raus.</div>').fadeIn();
},
error: function(data) {
$('.btn-contact-container').hide();
$('.contact-message').html('<i class="fa fa-exclamation contact-error"></i><div>Mist. Da ist was schief gegangen. Versuchs später nochmal.</div>').fadeIn();
}
}) //end ajax call
email.php
<?php
if($_REQUEST['first_name'] == '' || $_REQUEST['contact_email'] == '' || $_REQUEST['message'] == ''):
return "error";
endif;
if (filter_var($_REQUEST['contact_email'], FILTER_VALIDATE_EMAIL)):
$subject = 'Mail von der Hochzeitsseite: ' . $_REQUEST['contact_subject']; // Subject of your email
// Receiver email address
$to = 'my#mailadress.de';
// prepare header
$header = 'From: '. $_REQUEST['first_name'] . " " . $_REQUEST['last_name'] . ' <'. $_REQUEST['contact_email'] .'>'. "\r\n";
$header .= 'Reply-To: '. $_REQUEST['first_name'] . " " . $_REQUEST['last_name'] . ' <'. $_REQUEST['contact_email'] .'>'. "\r\n";
// $header .= 'Cc: ' . 'example#domain.com' . "\r\n";
// $header .= 'Bcc: ' . 'example#domain.com' . "\r\n";
$header .= 'X-Mailer: PHP/' . phpversion();
$message = $_REQUEST['message'] . "\n\n\n\n\n\n\n\n\n";
$message .= 'Name: ' . $_REQUEST['first_name'] . " " . $_REQUEST['last_name'] . "\n";
$message .= 'Email: ' . $_REQUEST['contact_email'] . "\n";
// Send contact information
$mail = mail( $to, $subject , $message, $header );
echo "success";
else:
return "error";
endif;
?>
Your form is getting submitted directly to email.php, it is not going through ajax. That's what the action attribute is all about:
<form id="contact-form" action="email.php"
To use ajax instead, you need to remove the action attribute from the form and add a click handler to your submit button/link. For example:
<button onclick="doAjaxCall()">Submit Email</button>
The ajax call itself, would look something like this:
$.ajax({
type: "POST",
url: "email.php",
data: {
name: $('#name').val(),
address: $('#address').val(),
...
},
...
Strange issue - my sendmail.php is working perfectly on desktop and on mobile devices only when requesting desktop websites (in Chrome app), but when using mobile site he does not work at all.
Can someone help me figure this out?
here is the code:
<?php
if(isset($_POST['email'])) {
if (!check_email($_POST['email']))
{
echo 'Please enter a valid email address<br />';
}
else send_email();
}
exit;
function check_email($emailAddress) {
if (filter_var($emailAddress, FILTER_VALIDATE_EMAIL)) {
return TRUE;
} else {
return FALSE;
}
}
function send_email() {
$message = "\nName: " . $_POST['name'] .
"\nEmail: " . $_POST['email'] ;
$message .= "\nMessage: " . $_POST['comment'] .
"\n\nBrowser Info: " . $_SERVER["HTTP_USER_AGENT"] .
"\nIP: " . $_SERVER["REMOTE_ADDR"] .
"\n\nDate: " . date("Y-m-d h:i:s");
$siteEmail = $_POST['receiver'];
$emailTitle = $_POST['subject'];
$thankYouMessage = "Thank you for contacting us, we'll get back to you shortly.";
if(!mail($siteEmail, $emailTitle, $message, 'From: ' . $_POST['name'] . ' <' . $_POST['email'] . '>'))
{
echo 'error';
}
else
{
echo 'success';
}
}
?>
You must make sure the mobile form has these two elements:
It is being submitted using method="POST".
Your email input has the attribute and value name="email".
I demonstrate where these things are set in the following code. This is incomplete, of course, it's just designed to show you where the two required parts must be.
<form ... method="POST">
...
<input type="text" name="email" ... >
...
</form>
I need to mention one more thing ...
That being said, what you're doing here is EXTREMELY INSECURE. You are allowing someone to set an email's from and two address on a web form. A (not so) clever hacker can easily write a script to turn your server into an open relay for spam or other evil activities. At minimum, you should remove $_POST['receiver'] and replace with with a hard-coded email address or at least not something that can be altered by an end-user when they POST to your form.
So I drilled down and found that the mobile form is directing submissions through this PHP file which was 404.
The issue now is, even when this file is avaiable, emails are not sent...
' . "\r\n"; $headers .=
'From: ' . "\r\n"; $headers = 'MIME-Version: 1.0' .
"\r\n"; $headers .= 'Content-type: text/html; charset=utf-8' . "\r\n";
$message .= "Name: " . $name . ""; $message .= "Subject: "
. $subject . ""; $message .= "Email: " . $email . ""; $message .= "Message: " . $message_text . "";
mail($to, $subject, $message, $headers, "-f noreplay#info.com");
echo 1; }
if(isset($_POST['sendmail']) && $_POST['sendmail'] == 1){
send_mail(); } ?>
I have set up the google reCaptcha PHP plugin on this site:
http://benliger.webatu.com/
You can see it displays fine under Contact, however after adding in the necessary PHP into my form_process file the form still submits regardless of whether or not the reCaptcha is filled out. Here is my PHP code that sits in the form_process file:
<?php
//Check if POST data is set, and not empty, else it will do this every single time, submitted or not
require_once('recaptchalib.php');
$privatekey = "6Le2a_oSAAAAAJ81_yQvCelFMIHiUcG_k6u0S1fd";
$resp = recaptcha_check_answer ($privatekey,
$_SERVER["REMOTE_ADDR"],
$_POST["recaptcha_challenge_field"],
$_POST["recaptcha_response_field"]);
if (!$resp->is_valid) {
// What happens when the CAPTCHA was entered incorrectly
die ("The reCAPTCHA wasn't entered correctly. Go back and try it again." .
"(reCAPTCHA said: " . $resp->error . ")");
} else {
if(isset($_POST) && !empty($_POST))
{
$mail_to = 'benliger#hotmail.com'; // specify your email here
// Assigning data from the $_POST array to variables
$name = $_POST['sender_name'];
$mail_from = $_POST['sender_email'];
$phone = $_POST['sender_phone'];
$message = $_POST['sender_message'];
// Construct email subject
$subject = 'enquiry ' . $name;
// Construct email body
$body_message = 'From: ' . $name . "\r\n";
$body_message .= 'E-mail: ' . $mail_from . "\r\n";
$body_message .= 'Phone: ' . $phone . "\r\n";
$body_message .= 'Message: ' . $message;
// Construct email headers
$headers = 'From: ' . $mail_from . "\r\n";
$headers .= 'Reply-To: ' . $mail_from . "\r\n";
$mail_sent = mail($mail_to, $subject, $body_message, $headers);
if ($mail_sent == true){
//Echo the message now, because it will be catched in your jQuery listerener (see code below)
echo 'Thanks for getting in touch!';
} else {
//Echo the message now, because it will be catched in your jQuery listerener (see code below)
echo 'Message not sent :( Please, get in contact with me directly: benliger#hotmail.com';
}
//This exit; is important, else the alert box will be full of the further html code
exit;
}
}
?>
And my HTML:
<form name="myForm" action="form_process.php" method="POST">
<?php
require_once('recaptchalib.php');
$publickey = "6Le2a_oSAAAAAEHu4u35QWlLzxzCYB1JnhFoI0u5"; // you got this from the signup page
echo recaptcha_get_html($publickey);
?>
.... and the rest of my form here
Might be worth noting my send button looks like so:
<input class="sendbutton" type="submit" name="send_message" value="Send">
Javascript:
$(document).on('submit','form',function(e){
//Prevent the default action
e.preventDefault();
var form = $(this);
//Create an array of input values
var data = $(this).serializeArray();
//Do the ajax request
$.post('form_process.php',data,function(responseMessage){
resetForm(form);
//Alert your message
$( ".mycontactform" ).html('<p>Thanks for getting in touchaaa!</p>');
//alert(responseMessage);
});
});
Error is in your jquery code .whatever the response is you are replacing it with
<p>Thanks for getting in touchaaa!</p>
use alert(responseMessage) to see the response
so replace $( ".mycontactform" ).html('<p>Thanks for getting in touchaaa!</p>');
with alert(responseMessage)
I tried earlier with no solution, so I'm adding all my code to try and resolve this issue. I am not getting this form in my inbox, but my ajax function is working like it should. I have godaddy hosting, and am running it locally on wampp for mac. I've tried multiple different email addresses with no avail. I don't want to use php mailer. I just want this to function properly instead of what it seems to be doing which is shooting emails into outter space
html
<div class="block">
<div class="done">
<h1>Thank you! I have received your message.</h1>
</div>
<div class="form">
<form method="post" action="scripts/process.php">
<input name="name" class="text" placeholder="Name" type="text" />
<input name="email" class="text" placeholder="Email" type="text" />
<textarea name="comment" class="text textarea" placeholder="Comment"></textarea>
<input name="submit" value="Let's Go!" id="submit" type="submit" />
<div class="loading"></div>
</form></div>
</div>
<div class="clear"></div>
</div>
</div>
jquery validation and ajax
$('#submit').click(function () {
//Get the data from all the fields
var name = $('input[name=name]');
var email = $('input[name=email]');
var comment = $('textarea[name=comment]');
var emailReg = /^([\w-\.]+#([\w-]+\.)+[\w-]{2,4})?$/;
var emailVal = email.val();
//Simple validation to make sure user entered something
//If error found, add hightlight class to the text field
if (!emailReg.test(emailVal)){
email.addClass('hightlight');
return false;
} else email.removeClass('hightlight');
if (name.val()=='') {
name.addClass('hightlight');
}else{name.removeClass('hightlight');}
if (email.val()=='') {
email.addClass('hightlight');
}else{email.removeClass('hightlight');}
if (comment.val()=='') {
comment.addClass('hightlight');
}else{email.removeClass('hightlight');}
if (name.val()=='' || email.val()=='' || comment.val()=='') {
return false;
}
//organize the data properly
var data = 'name=' + name.val() + '&email=' + email.val() + '&website='
+ website.val() + '&comment=' + encodeURIComponent(comment.val());
//disabled all the text fields
$('.text').attr('disabled','true');
//show the loading sign
$('.loading').show();
//start the ajax
$.ajax({
//this is the php file that processes the data and send mail
url: "scripts/process.php",
//GET method is used
type: "GET",
//pass the data
data: data,
//Do not cache the page
cache: false,
//success
success: function (html) {
//if process.php returned 1/true (send mail success)
if (html==1) {
//hide the form
$('.form').fadeOut('slow');
//show the success message
$('.done').fadeIn('slow');
//if process.php returned 0/false (send mail failed)
} else alert('Sorry, unexpected error. Please try again later.');
}
});
//cancel the submit button default behaviours
return false;
});
and the php which I regret to say I know very little about for now
<?php
//Retrieve form data.
//GET - user submitted data using AJAX
//POST - in case user does not support javascript, we'll use POST instead
$name = ($_GET['name']) ? $_GET['name'] : $_POST['name'];
$email = ($_GET['email']) ?$_GET['email'] : $_POST['email'];
$comment = ($_GET['comment']) ?$_GET['comment'] : $_POST['comment'];
//flag to indicate which method it uses. If POST set it to 1
if ($_POST) $post=1;
//Simple server side validation for POST data, of course,
//you should validate the email
if (!$name) $errors[count($errors)] = 'Please enter your name.';
if (!$email) $errors[count($errors)] = 'Please enter your email.';
if (!$comment) $errors[count($errors)] = 'Please enter your comment.';
//if the errors array is empty, send the mail
if (!$errors) {
//recipient - change this to your name and email
$to = 'myemail#gmail.com';
//sender
$from = $name . ' <' . $email . '>';
//subject and the html message
$subject = 'Comment from ' . $name;
$message = '
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head></head>
<body>
<table>
<tr><td>Name</td><td>' . $name . '</td></tr>
<tr><td>Email</td><td>' . $email . '</td></tr>
<tr><td>Comment</td><td>' . nl2br($comment) . '</td></tr>
</table>
</body>
</html>';
//send the mail
$result = sendmail($to, $subject, $message, $from);
//if POST was used, display the message straight away
if ($_POST) {
if ($result) echo 'Thank you! Matt has received your message.';
else echo 'Sorry, unexpected error. Please try again later';
//else if GET was used, return the boolean value so that
//ajax script can react accordingly
//1 means success, 0 means failed
} else {
echo $result;
}
//if the errors array has values
} else {
//display the errors message
for ($i=0; $i<count($errors); $i++) echo $errors[$i] . '<br/>';
echo 'Back';
exit;
}
//Simple mail function with HTML header
function sendmail($to, $subject, $message, $from) {
$headers = "MIME-Version: 1.0" . "\r\n";
$headers .= "Content-type:text/html;charset=iso-8859-1" . "\r\n";
$headers .= 'From: ' . $from . "\r\n";
$result = mail($to,$subject,$message,$headers);
if ($result) return 1;
else return 0;
}
?>
There are so many issues on sending PHP mails to different mail servers. For example, when I want to send email to GMail hosts I never include \r for new lines and I only go with \n. Maybe your problem is with your headers, I place my code here and see what you can get:
function send($address, $subject, $content, $from = '', $html = FALSE, $encoding = 'utf-8')
{
if(empty($address) || empty($content)) return;
$headers = "";
if($from != '')
{
$headers .= "From: {$from}\n";
$headers .= "Reply-To: {$from}\n";
}
$headers .= "To: {$address}\n";
if($html)
{
$headers .= "MIME-Version: 1.0\n";
$headers .= "Content-Type: text/html; charset={$encoding}\n";
$headers .= "Content-Transfer-Encoding: 8bit\n";
}
$headers .= "X-Priority: 1 (Highest)\n";
$headers .= "X-MSMail-Priority: High\n";
$headers .= "Importance: High\n";
$headers .= "X-Mailer: PHP/" . phpversion();
set_time_limit(30);
mail($address, $subject, $content, $headers);
}
send('myemail#myhost.com', 'title', 'content', 'myemail <myemail#myhost.com>', FALSE);
is possible to use php to reset a form without refresh?
how can i archive this?
or is possible to do it with js?
most important is do it without to refresh the page and dont add another button for this(that's because the design)
any idea?
thanks
am working with recaptcha on my form and once i submitted the information i want to send a message
this is my js code
function validateCaptcha(){
challengeField = $("input#recaptcha_challenge_field").val();
responseField = $("input#recaptcha_response_field").val();
nameField = $("input#name").val();
emailField = $("input#email").val();
phoneField =$("input#phone").val();
reasonField =$("select#reason").val();
messageField =$("textarea#message").val();
var html = $.ajax({
type: "POST",
url: "ajax.recaptcha.php",
data: "recaptcha_challenge_field=" + challengeField + "&recaptcha_response_field=" + responseField +"&name="+ nameField +"&email=" + emailField +"&phone="+ phoneField + "&reason=" + reasonField +"&message=" + messageField,
async: false
}).responseText;
if(html == "success")
{
$("#captchaStatus").html("Success. Submitting form.");
$("#thanks").html("Thank you, we going to keep in touch with you soon. ");
return false;
}
else
{
$("#captchaStatus").html("Your captcha is incorrect. Please try again");
Recaptcha.reload();
return false;
}
}
this is my php code
$name = $_POST['name'];
$email = $_POST['email'];
$phone = $_POST['phone'];
$reason = $_POST['reason'];
$message = $_POST['message'] ;
if (empty($name)|| empty($email) || empty($message))
{
}
else
{
$resp = recaptcha_check_answer (PRIVATEKEY, $_SERVER["REMOTE_ADDR"], $_POST["recaptcha_challenge_field"], $_POST["recaptcha_response_field"]);
if ($resp->is_valid) {
$header = 'From: ' . $email . " \r\n";
$msg = "Sent from: " . $name . "\r\n";
$msg .= "Email: " . $email . " \r\n";
$msg .= "Phone: " . $phone . " \r\n";
$msg .= "Contact reason:" . $reason . " \r\n";
$msg .= "Message: " . $message . " \r\n";
$to = 'patricia#anetdesign.com';
$subject = 'Emailmakers contact page';
mail($to, $subject, utf8_decode($msg), $header);
?>success<?
}
else
{
die ("The reCAPTCHA wasn't entered correctly. Go back and try it again." .
"(reCAPTCHA said: " . $resp->error . ")");
}
}
Well, once you sed the ajax request if the captcha fails then just reload the entire form.
Say you have only the form in myform.php and you include it in your main page, when the captcha does not match you can just reload the form. Like this:
if (html != "Success")
{
$("#divThatHoldsTheForm").html(html)
}
and in your myform.php you have only:
<form action="..." method="POST">
<!-- some inputs -->
</form>
Use the reset() function. If you have a form named frm then use can use frm.reset().
Or just write code to first get all textboxes and set its value attribute to "". this wont need to refresh your page
Using PHP mean refreshing the page (only in case of ajax) so i suggest you try to use javascript instead of php to this task