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
Related
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);
}
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 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.
My contact form is not including message and other informations in emails.
There is 'Unknown sender' and 'No subject'. Email contains my tags (from:, subject:, message:) but no content is written after them.
I have tried a few other scripts, but they gave the same result.
My JS code
(function($){
$(document).ready(function() {
$('#submit-form').click(function(e){
e.preventDefault();
var reg = /^([A-Za-z0-9_\-\.])+\#([A-Za-z0-9_\-\.])+\.([A-Za-z]{2,4})$/;
var name = $('#rp_name').val(),
email = $('#rp_email').val(),
subject = $('#rp_subject').val(),
message = $('#rp_message').val(),
data_html,
success = $('#success');
if(name === ""){
$('#rp_name').val('Please enter your name.');
}
if(subject === ""){
$('#rp_subject').val('Please enter your name.');
}
if(email === ""){
$('#rp_email').val('Your email is required.');
}else if(reg.test(email) === false){
$('#rp_email').val('Invalid Email Address.');
}
if(message === ""){
$('#rp_message').val('Message is required.');
}
if(message !== "" && name !== "" && reg.test(email) !== false) {
data_html = "name=" + name + "&email="+ email + "&message=" + message + "&subject="+ subject;
alert(data_html);
$.ajax({
type: 'POST',
url: 'php_helpers/contact_form.php',
data: data_html,
success: function(msg){
if (msg == 'sent'){
success.html('<div class="alert alert-success">Message <strong>successfully</strong> sent!</div>') ;
$('#rp_name').val('');
$('#rp_email').val('');
$('#rp_message').val('');
}else{
success.html('<div class="alert alert-error">Message <strong>not</strong> sent! Please Try Again!</div>') ;
}
}
});
}
return false;
});
});
})(jQuery);
My PHP code
<?php
$to = 'email'; // I changed it
$subject = $_POST['subject'];
if($to) {
$name = $_POST['name'];
$email = $_POST['email'];
$fields = array(
0 => array(
'text' => 'Imie',
'val' => $_POST['name']
),
1 => array(
'text' => 'Email',
'val' => $_POST['email']
),
2 => array(
'text' => 'WIADOMOSC',
'val' => $_POST['message']
)
);
$message = "";
foreach($fields as $field) {
$message .= $field['text'].": " . htmlspecialchars($field['val'], ENT_QUOTES) . "<br>\n";
}
$$headers = 'MIME-Version: 1.0' . "\r\n";
$headers .= 'Content-type: text/html; charset=utf-8' . "\r\n";
$headers .= 'From: '. $email . "\r\n" . 'X-Mailer: PHP/' . phpversion();
mail($to, $subject, $message, $headers);
if ($message){
echo 'sent';
}else{
echo 'failed';
}
} else {
echo "Don't access this file directly";
}
?>
I'll be glad for any hints.
There as i check your contact.php file code is ok. But you need one thing if use firefox. please console your code.I mean when you open firebug there will be one option console. with help you can check is your value along with variable is going or they empty.
I think your value is not going to PHP file. use console and you can easily bug your value.
I hope this make sense for you.
Check if your php script receives name, email and message. You can check it using
var_dump($_POST);
If server doesn't receive these variables, try to send data_html as an object:
change
data: data_html,
to
data: {name: name, email: email, message: message}
I didn't test it, but I always use this way of sending data from js to server.
You are using two dollar symbols in the line: $$headers = 'MIME-Version: 1.0' . "\r\n"; Please remove "$" and try again.
Thanks for all your responses. I finally manage to find a solution. I haven't used firebug before, but thanks to it I could find the error message. Now the script is working fine.
It wasn't in code, but in .htaccess rewrite rule for .php files which was couseing 301 error for ajax request (../contact instead of ../contact.php).
I have one .php page (file uploader) and I thought that adding another seo-friendly link rule for it would be a good idea.
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)