I have a problem with reloading the page. After clicking submit form the page reloads. I click send the form and takes me to http: // localhost: 3000 / mail.php. And I would like the site not to be reloaded. (I use the validation form jquery plugin).This is my code:
jquery
(function(){
$("#contactForm").on('submit', function(e) {
e.preventDefault();
var data = {
name = $('#field-name').val(),
phone = $('#field-phone').val(),
email = $('#field-email').val(),
message = $('#field-message').val()
};
$.ajax({
type: "POST",
url: "mail.php",
data: data,
success: function(){
console.log("jej");
}
});
return false;
});
});
and php code
<?php
$to = 'name#gmail.com';
$name = $_POST['name'];
$phone = $_POST['phone'];
$email= $_POST['email'];
$text = $_POST['message'];
$subject = 'Nowy e-mail od ' . $name . ' (' . $email . ')';
$message = $name . $phone . $email . $text;
$headers = 'From: ' . $name . "\r\n" .
if(mail($to, $subject, $message, $headers)) {
print "<p class='success'>Mail Sent.</p>";
} else {
print "<p class='Error'>Problem in Sending Mail.</p>";
}
?>
change part of your code
$("#contactForm").on('submit', function(e)
to this...
$("#contactFormButton").on('click', function(e)
and change your submit button to this...
<button id="contactFormButton" type="button" class="form-control">Submit</button>
and here your php code...
if(mail($to, $subject, $message, $headers)) {
echo "Mail Sent!";
} else {
echo "Error!!";
}
and here you can catch result of your php code...
success: function(data){
console.log(data);
}
Related
I'm having trouble sending emails using ajax and recaptcha. I'm using 2 different files, my contact form and ajax code is on the index.html and the php code to validade the recaptcha and send the email is the email.php.
This is my ajax code, it is inside the body tag at the bottom of the page
<script>
$(".contact-card").submit(function(e){
e.preventDefault();
var name = $("#name").val();
var email = $("#email").val();
var message = $("#message").val();
var dataString = 'name=' + name + '&email=' + email + '&message=' + message;
function isValidEmail(emailAddress) {
var pattern = new RegExp(/^((([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+(\.([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+)*)|((\x22)((((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(([\x01-\x08\x0b\x0c\x0e-\x1f\x7f]|\x21|[\x23-\x5b]|[\x5d-\x7e]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(\\([\x01-\x09\x0b\x0c\x0d-\x7f]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]))))*(((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(\x22)))#((([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.)+(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.?$/i);
return pattern.test(emailAddress);
};
if (isValidEmail(email)){
$.ajax({
type: "POST",
url: "email.php",
data: dataString,
success: function(){
$('.success').fadeIn(1000).delay(3000).fadeOut(1000);
}
});
} else{
$('.error').fadeIn(1000).delay(3000).fadeOut(1000);
}
return false;
});
</script>
and this is my php file called email.php
<?php
error_reporting(0);
if(isset($_POST['submit'])){
$to = "EMAIL";
$subject = "test";
$name = $_POST['name'];
$email = $_POST['email'];
$message = $_POST['message'];
$msgBody = 'Name: ' .$name. ' Message: ' .$message;
$headers = 'From: ' .$email;
$secretKey = "";
$responseKey = $_POST['g-recaptcha-response'];
$url = "https://www.google.com/recaptcha/api/siteverify?secret=$secretKey&response=$responseKey";
$response = file_get_contents($url);
$response = json_decode($response);
if($response -> success){
if( mail($to, $subject, $msgBody, $headers)){
echo ("Success");
} else{
echo ("failed");
var_dump($_POST);
}
} else{
echo ("verification failed");
}
}
?>
I'm not using action on my form in the html.
Please help!!!
thank you!!
So I am currently utilizing a HTML form to obtain information from customers (in a landing page context) that sends via email all the information that the user submitted, and it's working fine so far.
However, I've added a file upload field to the HTML form ($userfile) but I wasn't able to handle the file upload and attachment properly. I've been testing and tweaking around a lot, but I can never seem to get it working.
This is the PHP file that I'm currently utilizing, based on a pre-existing template.
$to = "email#email.com";
$nome = $_POST["nome"];
$email = $_POST["email"];
$website = (isset($_SERVER['HTTPS']) ? "https" : "http") . "://$_SERVER[HTTP_HOST]$_SERVER[REQUEST_URI]";
if (isset($email) && isset($nome)) {
$subject = "Lead: $nome";
$headers = "MIME-Version: 1.0" . "\r\n";
$headers .= "Content-type:text/html;charset=iso-8859-1" . "\r\n";
$headers .= "From: ".$nome." <".$email.">\r\n"."Reply-To: ".$email."\r\n" ;
$msg = 'Hey Admin, <br/> <br/> Here are the details:';
$msg .= ' <br/> <br/> <table border="1" cellpadding="6" cellspacing="0" style="border: 1px solid #eeeeee;">';
foreach ($_POST as $label => $value) {
$msg .= "<tr><td width='100'>". ucfirst($label) . "</td><td width='300'>" . $value . " </tr>";
}
$msg .= " </table> <br> --- <br>Sent by $website";
$mail = mail($to, $subject, $msg, $headers);
if($mail) {
echo 'success';
} else {
echo 'failed';
}
} // END isset
?>
And also the AJAX POST
var dataString = $(form).serialize();
/*
AJAX POST
--------- */
$.ajax({
type: "POST",
data: dataString,
url: "php/contact.php",
cache: false,
success: function(d) {
$(".form-group").removeClass("has-success");
if (d == 'success') {
if (noredirect) {
$('#js-contact-result').fadeIn('slow').html('<div class="alert alert-success top-space">' + success_msg + '</div>').delay(3000).fadeOut('slow');
} else {
window.location.href = redirect;
}
} else {
$('#js-contact-result').fadeIn('slow').html('<div class="alert alert-danger top-space">' + error_msg + '</div>').delay(3000).fadeOut('slow');
}
$("#js-contact-btn").attr("disabled", false);
}
});
If anyone could point me to some resources where I can learn more or actually help me solve it, I would really appreciate it. Thank you!
var dataString = $(form).serialize();
does not allow for uploading files
instead use a formdata javascript object
var dataString = new FormData(form);
You cannot use form.serialize() for file input.
Check here: jQuery Ajax File Upload
I got the messege to apear in the DIV tag but not sure how to send the email address onto the external email database //myguestlist.com/mgl/formreceiver.php.
here is the HTML
Be the first to know about the Channel Seven Brisbane Racing
Carnival:
method="post" id="mf528c0a39d76be"> <input class="mailchimp-input"
input="" name="PatronEmail" id="mf528c0a39d76be_PatronEmail"
placeholder="Enter your email..." type="text"> <button type="submit"
class="btn"><span class="singup-image"><img src="img/send.png"
alt="send email"></span><span class="singup-text">Send</span></button>
</form>
<div class="success-message"></div>
<div class="error-message"></div>
</div>
Here is the PHP:
<?php
// Email address verification
function isEmail($email) {
return(preg_match("/^[-_.[:alnum:]]+#((([[:alnum:]]|[[:alnum:]][[:alnum:]-]*[[:alnum:]]).)+(ad|ae|aero|af|ag|ai|al|am|an|ao|aq|ar|arpa|as|at|au|aw|az|ba|bb|bd|be|bf|bg|bh|bi|biz|bj|bm|bn|bo|br|bs|bt|bv|bw|by|bz|ca|cc|cd|cf|cg|ch|ci|ck|cl|cm|cn|co|com|coop|cr|cs|cu|cv|cx|cy|cz|de|dj|dk|dm|do|dz|ec|edu|ee|eg|eh|er|es|et|eu|fi|fj|fk|fm|fo|fr|ga|gb|gd|ge|gf|gh|gi|gl|gm|gn|gov|gp|gq|gr|gs|gt|gu|gw|gy|hk|hm|hn|hr|ht|hu|id|ie|il|in|info|int|io|iq|ir|is|it|jm|jo|jp|ke|kg|kh|ki|km|kn|kp|kr|kw|ky|kz|la|lb|lc|li|lk|lr|ls|lt|lu|lv|ly|ma|mc|md|mg|mh|mil|mk|ml|mm|mn|mo|mp|mq|mr|ms|mt|mu|museum|mv|mw|mx|my|mz|na|name|nc|ne|net|nf|ng|ni|nl|no|np|nr|nt|nu|nz|om|org|pa|pe|pf|pg|ph|pk|pl|pm|pn|pr|pro|ps|pt|pw|py|qa|re|ro|ru|rw|sa|sb|sc|sd|se|sg|sh|si|sj|sk|sl|sm|sn|so|sr|st|su|sv|sy|sz|tc|td|tf|tg|th|tj|tk|tm|tn|to|tp|tr|tt|tv|tw|tz|ua|ug|uk|um|us|uy|uz|va|vc|ve|vg|vi|vn|vu|wf|ws|ye|yt|yu|za|zm|zw)$|(([0-9][0-9]?|[0-1][0-9][0-9]|[2][0-4][0-9]|[2][5][0-5]).){3}([0-9][0-9]?|[0-1][0-9][0-9]|[2][0-4][0-9]|[2][5][0-5]))$/i", $email));
}
if($_POST) {
// Enter the email where you want to receive the notification when someone subscribes
$emailTo = 'wbriton#brc.com.au';
$subscriber_email = ($_POST['PatronEmail']);
if(!isEmail($subscriber_Email)) {
$array = array();
$array['valid'] = 0;
$array['message'] = 'Insert a valid email address!';
echo json_encode($array);
}
else {
$array = array();
$array['valid'] = 1;
$array['message'] = 'Thanks for your subscription!';
echo json_encode($array);
// Send email
$subject = 'New Subscriber!';
$body = "You have a new subscriber!\n\nEmail: " . $subscriber_email;
// uncomment this to set the From and Reply-To emails, then pass the $headers variable to the "mail" function below
//$headers = "From: ".$subscriber_email." <" . $subscriber_email . ">" . "\r\n" . "Reply-To: " . $subscriber_email;
mail($emailTo, $subject, $body);
}
}
?>
And here is the Java Script
$('.success-message').hide();
$('.error-message').hide();
$('.subscribe form').submit(function() {
var postdata = $('.subscribe form').serialize();
$.ajax({
type: 'POST',
url: 'php/sendmail.php',
data: postdata,
dataType: 'json',
success: function(json) {
if(json.valid == 0) {
$('.success-message').hide();
$('.error-message').hide();
$('.error-message').html(json.message);
$('.error-message').fadeIn();
}
else {
$('.error-message').hide();
$('.success-message').hide();
$('.subscribe form').hide();
$('.success-message').html(json.message);
$('.success-message').fadeIn();
}
}
});
return false;
});
I'm making a simple contact form, I have an old school php mailer mail.php and a jQuery front page from where I'm calling it.
As I wanted it to work, it should've stayed on same page, but it actually jumps to mail.php and displays the message
Thank you for contacting me. I'll try to reach you ASAP.
Though it does send the mail, thats still not acceptable as that was not my intention. Can anybody find out what I'm doing wrong here ?
Any help appreciated.
PHP:
<?php
$name = trim($_POST['name']);
$email = trim($_POST['email']);
if(function_exists('stripslashes')) {
$message = stripslashes(trim($_POST['message']));
} else {
$message = trim($_POST['message']);
}
$emailTo = 'myEmail#gmail.com';
$subject = 'Contact Form Submission from '.$name;
$sendCopy = trim($_POST['sendCopy']);
$body = "Name: $name \n\nEmail: $email \n\nMessage: $message";
$headers = 'From: Saddi website <'.$emailTo.'>' . "\r\n" . 'Reply-To: ' . $email;
mail($emailTo, $subject, $body, $headers);
echo "Thank you for contacting me. I'll try to reach you ASAP.";
return true;
?>
FORM (Lot of bootstrap tags there, so to keep it clean I'm just posting ):
<form class="form" action="mail.php" method="post" id="contact-form">
</form>
And here goes my AJAX:
var data_string = jQuery('#contact-form').serialize();
jQuery.ajax({
type: "POST",
url: "mail.php",
data: {name:name,email:email,message:message},
timeout: 6000,
error: function(request,error) {
if (error == "timeout") {
jQuery('#timedout').fadeIn('slow');
setTimeout(function() {
jQuery('#timedout').fadeOut('slow');
}, 3000);
}
else {
jQuery('#state').fadeIn('slow');
jQuery("#state").html('The following error occured: ' + error + '');
setTimeout(function() {
jQuery('#state').fadeOut('slow');
}, 3000);
}
},
success: function() {
jQuery('span.valid').remove();
jQuery('#thanks').fadeIn('slow');
jQuery('input').val('');
jQuery('textarea').val('');
setTimeout(function() {
jQuery('#thanks').fadeOut('slow');
}, 3000);
}
First i will recommend you to use jQuery Form Plugin, very helpful for this kind of ajax post and validations.
jQuery Form
Second, you can use event.preventDefault(); to avoid the default action of the link but it will really depend on how are you triggering your form to the ajax code
event.preventDefault
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