I think there is something wrong with my javascript.
I have (html) form:
<html><form action="wp-content/themes/devwp-child/action_page.php" method="post">
<fieldset>
<input type="text" name="ime" placeholder="Ime *">
<input type="text" name="priimek" placeholder="Priimek *">
<input type="email" name="email" placeholder="E-poštni naslov*">
<input type="text" name="telefonska" placeholder="Telefonska številka">
<input type="text" name="podjetje" placeholder="Podjetje">
</fieldset>
<p id="izberi">IZBERI</p>
<fieldset>
<input type = "radio" name = "subject" value = "maths"> Maths
<input type = "radio" name = "subject" value = "physics"> Physics
</fieldset>
<fieldset>
<textarea name="field3" placeholder="Vaše želje"></textarea>
</fieldset>
<input type="submit" value="send" />
</form>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"</script>
<script src="main.js"</script>
</html>
Then i have 2 files:
-main.js
-action_page.php
action_page.php code:
<?php
// Only process POST reqeusts.
if ($_SERVER["REQUEST_METHOD"] == "POST") {
// Get the form fields and remove whitespace.
$ime = strip_tags(trim($_POST["ime"]));
$name = str_replace(array("\r","\n"),array(" "," "),$name);
$email = filter_var(trim($_POST["email"]), FILTER_SANITIZE_EMAIL);
// Check that data was sent to the mailer.
if ( empty($ime) OR !filter_var($email, FILTER_VALIDATE_EMAIL)) {
// Set a 400 (bad request) response code and exit.
http_response_code(400);
echo "Oops! There was a problem with your submission. Please complete the form and try again.";
exit;
}
// Set the recipient email address.
// FIXME: Update this to your desired email address.
$recipient = "ptlabdoo#gmail.com";
// Set the email subject.
$subject = "New contact from $name";
// Build the email content.
$email_content = "Name: $name\n";
$email_content .= "Email: $email\n\n";
$email_content .= "Message:\n$message\n";
// Build the email headers.
$email_headers = "From: $name <$email>";
// Send the email.
if (mail($recipient, $subject, $email_content, $email_headers)) {
// Set a 200 (okay) response code.
http_response_code(200);
echo "Thank You! Your message has been sent.";
} else {
// Set a 500 (internal server error) response code.
http_response_code(500);
echo "Oops! Something went wrong and we couldn't send your message.";
}
} else {
// Not a POST request, set a 403 (forbidden) response code.
http_response_code(403);
echo "There was a problem with your submission, please try again.";
}
?>
If form is properly full then it sends an email - that words fine; but if form is not full then i get:
Forbidden
You don't have permission to access /wp-content/themes/devwp-child/action_page.php on this server.
Additionally, a 400 Bad Request error was encountered while trying to use an ErrorDocument to handle the request.
main.js code:
$(function() {
// Get the form.
var form = $('#ajax-contact');
// Get the messages div.
var formMessages = $('#form-messages');
// Set up an event listener for the contact form.
$(form).submit(function(event) {
// Stop the browser from submitting the form.
event.preventDefault();
// Serialize the form data.
var formData = $(form).serialize();
});
});
// Submit the form using AJAX.
$.ajax({
type: 'POST',
url: $(form).attr('action'),
data: formData
})
.done(function(response) {
// Make sure that the formMessages div has the 'success' class.
$(formMessages).removeClass('error');
$(formMessages).addClass('success');
// Set the message text.
$(formMessages).text(response);
// Clear the form.
$('#name').val('');
$('#email').val('');
$('#message').val('');
})
.fail(function(data) {
// Make sure that the formMessages div has the 'error' class.
$(formMessages).removeClass('success');
$(formMessages).addClass('error');
// Set the message text.
if (data.responseText !== '') {
$(formMessages).text(data.responseText);
} else {
$(formMessages).text('Oops! An error occured and your message could not be sent.');
}
});
Related
I'm trying to send an email to myself with the text that has been entered in the textbox.
<form class="form align-center" id="mailchimp">
<div class="row">
<div class="col-md-8 col-md-offset-2">
<div class="newsletter-label font-alt">
Stay informed with our newsletter
</div>
<div class="mb-20">
<input placeholder="Enter Your Email" class="newsletter-field form-control input-md round mb-xs-10"
name="emaill" type="email" pattern=".{5,100}" required aria-required="true">
<button type="submit" aria-controls="subscribe-result" id="submit_btnn"
class="btn btn-mod btn-medium btn-round mb-xs-10">
Subscribe
</button>
</div>
<div class="form-tip">
<i class="fa fa-info-circle"></i> Please trust us, we will never send you spam
</div>
<div id="subscribe-result" role="region" aria-live="polite" aria-atomic="true"></div>
After that I catch it in Js
$(document).ready(function(){
$("#submit_btnn").click(function(){
//get input field values
var user_email = $('input[name=emaill]').val();
//simple validation at client's end
var proceed = true;
//we simply change border color to red if empty field using .css()
if (user_email == "") {
$('input[name=email]').css('border-color', '#e41919');
proceed = false;
}
//everything looks good! proceed...
if (proceed) {
//data to be sent to server
post_data = {
'userEmail': user_email
};
console.log(post_data);
//Ajax post data to server
$.post('nieuwsbrief.php', post_data, function(response){
//load json data from server and output message
if (response.type == 'error') {
output = '<div class="error">' + response.text + '</div>';
}
else {
output = '<div class="success">' + response.text + '</div>';
}
$("#subscribe-result").hide().html(output).slideDown();
}, 'json');
}
return false;
});
//reset previously set border colors and hide all message on .keyup()
$("#contact_form input, #contact_form textarea").keyup(function(){
$("#contact_form input, #contact_form textarea").css('border-color', '');
$("#subscribe-result").slideUp();
});
});
After that I want to use the Ajax post to send it to my php file
<?php
if($_POST)
{
echo '<script>console.log($_POST["userEmail"])</script>';
$to_Email = "mathias#wizewolf.com"; //Replace with recipient email address
$subject = 'Message from website '.$_SERVER['SERVER_NAME']; //Subject line for emails
echo '<script>console.log(to_Email)</script>';
//check if its an ajax request, exit if not
if(!isset($_SERVER['HTTP_X_REQUESTED_WITH']) AND strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) != 'xmlhttprequest') {
//exit script outputting json data
$output = json_encode(
array(
'type'=>'error',
'text' => 'Request must come from Ajax'
));
die($output);
}
//check $_POST vars are set, exit if any missing
if(!isset($_POST["userEmail"]))
{
$output = json_encode(array('type'=>'error', 'text' => 'Input fields are empty!'));
die($output);
}
//Sanitize input data using PHP filter_var().
$user_Email = filter_var($_POST["userEmail"], FILTER_SANITIZE_EMAIL);
$user_Message = "d";
$user_Message = str_replace("\'", "'", $user_Message);
$user_Message = str_replace("'", "'", $user_Message);
//additional php validation
if(strlen($user_Name)<4) // If length is less than 4 it will throw an HTTP error.
{
$output = json_encode(array('type'=>'error', 'text' => 'Name is too short or empty!'));
die($output);
}
if(!filter_var($user_Email, FILTER_VALIDATE_EMAIL)) //email validation
{
$output = json_encode(array('type'=>'error', 'text' => 'Please enter a valid email!'));
die($output);
}
if(strlen($user_Message)<5) //check emtpy message
{
$output = json_encode(array('type'=>'error', 'text' => 'Too short message! Please enter something.'));
die($output);
}
//proceed with PHP email.
$headers = 'From: '.$user_Email.'' . "\r\n" .
'Reply-To: '.$user_Email.'' . "\r\n" .
'X-Mailer: PHP/' . phpversion();
$sentMail = #mail($to_Email, $subject, $user_Message . "\r\n\n" .'-- '.$user_Name. "\r\n" .'-- '.$user_Email, $headers);
if(!$sentMail)
{
$output = json_encode(array('type'=>'error', 'text' => 'Could not send mail! Please check your PHP mail configuration.'));
die($output);
}else{
$output = json_encode(array('type'=>'message', 'text' => 'Hi '.$user_Name .'! Thank you for your email'));
die($output);
}
}
?>
With the console log, I've found out that until the start of the PHP file everything works. After that... not so much. All the tips and info are appreciated.
Instead of using jQuery and PHP, you could use STMP.js. I don't know how to answer this question with jQuery or PHP, but I know how to send emails with SMTP. I made an example on JSFiddle below. But, this might not work on JSFiddle for security reasons.
JSFiddle
https://jsfiddle.net/Yeet45687564/9prs4j2a/21/
// the javascript code below is also found on JSFiddle
let subject;
let body;
function setValues() {
// sets the values of the subject and body
subject = document.getElementById("emailSubject").value;
body = document.getElementById("emailBody").value;
}
function send() {
setValues();
// sends the email
Email.send({
Host: "smtp.gmail.com",
Username: "<sender's email address>",
Password: "<your email password>",
To: "<recipient's email address>",
From: "<sender’s email address>",
Subject: subject,
Body: body,
}).then(
// displays a message if the email was sent
message => alert("Your Email was sent.")
);
}
If you can't get this working, there is an SMTP tutorial on Pepipost.
https://pepipost.com/tutorials/how-to-send-emails-with-javascript/
But, using SMTP could be a huge security issue. Anyone who uses the inspect element on your website will be able to get your email password, unless you can block them from inspecting it and viewing the page source.
I have a jquery/ajax contact form and tried to add the Google reCAPTCHA v2, but it isn't working. The form worked before I included the reCAPTCHA. The reCAPTCHA shows up (although it takes forever to load), and I can verify that I'm not a robot (which takes forever as well), but when I click on my submit button, the spot where I display my status messages shows this, including the code, as text:
<!DOCTYPE HTML PUBLIC "-//IETF//DTD HTML 2.0//EN"> <html><head> <title>500 Internal Server Error</title> </head><body> <h1>Internal Server Error</h1> <p>The server encountered an internal error or misconfiguration and was unable to complete your request.</p> <p>Please contact the server administrator, and inform them of the time the error occurred, and anything you might have done that may have caused the error.</p> <p>More information about this error may be available in the server error log.</p> </body></html>
I can't figure out what's going wrong. I followed Google's instructions and included this just before my tag:
<script src='https://www.google.com/recaptcha/api.js'></script>
and integrated my form like this:
<div class="g-recaptcha" data-sitekey="6LeehAsUAAAAAILDfzizJ23GHH7yPGxWBFP_3tE7"></div>
I tried many different ways to integrate it in my mailer.php file without success, and I couldn't find many tutorials that address v2 specifically (not sure if it even matters). My most recent version of the mailer.php is based on an example I found on Google's recaptcha Github:
<?php
require_once __DIR__ . 'inc/autoload.php';
// If the form was submitted
if ($_SERVER["REQUEST_METHOD"] == "POST") {
// If the Google Recaptcha box was clicked
if(isset($_POST['g-recaptcha-response']) && !empty($_POST['g-recaptcha-response'])){
$siteKey = '6LeehAsUAAAAAILDfzizJ23GHH7yPGxWBFP_3tE7';
$secret = 'I-removed-this-for-now';
$recaptcha = new \ReCaptcha\ReCaptcha($secret);
$resp = $recaptcha->verify($gRecaptchaResponse, $remoteIp);
// If the Google Recaptcha check was successful
if ($resp->isSuccess()){
$name = strip_tags(trim($_POST["name"]));
$name = str_replace(array("\r","\n"),array(" "," "),$name);
$email = filter_var(trim($_POST["email"]), FILTER_SANITIZE_EMAIL);
$message = trim($_POST["message"]);
if ( empty($name) OR empty($message) OR !filter_var($email, FILTER_VALIDATE_EMAIL)) {
http_response_code(400);
echo "Oops! There was a problem with your submission. Please complete the form and try again.";
exit;
}
$recipient = "I-removed-this#for-now.com";
$subject = "New message from $name";
$email_content = "Name: $name\n";
$email_content .= "Email: $email\n\n";
$email_content .= "Message:\n$message\n";
$email_headers = "From: $name <$email>";
if (mail($recipient, $subject, $email_content, $email_headers)) {
http_response_code(200);
echo "Thank You! Your message has been sent.";
}
else {
http_response_code(500);
echo "Oops! Something went wrong, and we couldn't send your message. Check your email address.";
}
}
// If the Google Recaptcha check was not successful
else {
echo "Robot verification failed. Please try again.";
}
}
// If the Google Recaptcha box was not clicked
else {
echo "Please click the reCAPTCHA box.";
}
}
// If the form was not submitted
// Not a POST request, set a 403 (forbidden) response code.
else {
http_response_code(403);
echo "There was a problem with your submission, please try again.";
}
?>
This is the app.js that goes with my contact form (I haven't changed this at all when trying to include the reCAPTCHA):
$(function() {
// Get the form.
var form = $('#ajax-contact');
// Get the messages div.
var formMessages = $('#form-messages');
// Set up an event listener for the contact form.
$(form).submit(function(e) {
// Stop the browser from submitting the form.
e.preventDefault();
// Serialize the form data.
var formData = $(form).serialize();
// Submit the form using AJAX.
$.ajax({
type: 'POST',
url: $(form).attr('action'),
data: formData
})
.done(function(response) {
// Make sure that the formMessages div has the 'success' class.
$(formMessages).removeClass('error');
$(formMessages).addClass('success');
// Set the message text.
$(formMessages).text(response);
// Clear the form.
$('#name').val('');
$('#email').val('');
$('#message').val('');
})
.fail(function(data) {
// Make sure that the formMessages div has the 'error' class.
$(formMessages).removeClass('success');
$(formMessages).addClass('error');
// Set the message text.
if (data.responseText !== '') {
$(formMessages).text(data.responseText);
} else {
$(formMessages).text('Oops! An error occured, and your message could not be sent.');
}
});
});
});
The autoload.php comes directly from the Google Github, and I didn't make any changes:
<?php
/* An autoloader for ReCaptcha\Foo classes. This should be required()
* by the user before attempting to instantiate any of the ReCaptcha
* classes.
*/
spl_autoload_register(function ($class) {
if (substr($class, 0, 10) !== 'ReCaptcha\\') {
/* If the class does not lie under the "ReCaptcha" namespace,
* then we can exit immediately.
*/
return;
}
/* All of the classes have names like "ReCaptcha\Foo", so we need
* to replace the backslashes with frontslashes if we want the
* name to map directly to a location in the filesystem.
*/
$class = str_replace('\\', '/', $class);
/* First, check under the current directory. It is important that
* we look here first, so that we don't waste time searching for
* test classes in the common case.
*/
$path = dirname(__FILE__).'/'.$class.'.php';
if (is_readable($path)) {
require_once $path;
}
/* If we didn't find what we're looking for already, maybe it's
* a test class?
*/
$path = dirname(__FILE__).'/../tests/'.$class.'.php';
if (is_readable($path)) {
require_once $path;
}
});
I would really appreciate your help!
Okay, I fixed it. One reason it wasn't working was that I had to enable allow_url_fopen in php.ini.
Then I completely changed the code to get rid of that autoload.php and the class error. I didn't change app.js. The working mailer.php now looks like this:
<?php
// If the form was submitted
if ($_SERVER["REQUEST_METHOD"] == "POST") {
// If the Google Recaptcha box was clicked
if(isset($_POST['g-recaptcha-response']) && !empty($_POST['g-recaptcha-response'])){
$captcha=$_POST['g-recaptcha-response'];
$response=file_get_contents("https://www.google.com/recaptcha/api/siteverify?secret=MYKEY&response=".$captcha."&remoteip=".$_SERVER['REMOTE_ADDR']);
$obj = json_decode($response);
// If the Google Recaptcha check was successful
if($obj->success == true) {
$name = strip_tags(trim($_POST["name"]));
$name = str_replace(array("\r","\n"),array(" "," "),$name);
$email = filter_var(trim($_POST["email"]), FILTER_SANITIZE_EMAIL);
$message = trim($_POST["message"]);
if ( empty($name) OR empty($message) OR !filter_var($email, FILTER_VALIDATE_EMAIL)) {
http_response_code(400);
echo "Oops! There was a problem with your submission. Please complete the form and try again.";
exit;
}
$recipient = "I-removed-this#for-now.com";
$subject = "New message from $name";
$email_content = "Name: $name\n";
$email_content .= "Email: $email\n\n";
$email_content .= "Message:\n$message\n";
$email_headers = "From: $name <$email>";
if (mail($recipient, $subject, $email_content, $email_headers)) {
http_response_code(200);
echo "Thank You! Your message has been sent.";
}
else {
http_response_code(500);
echo "Oops! Something went wrong, and we couldn't send your message. Check your email address.";
}
}
// If the Google Recaptcha check was not successful
else {
echo "Robot verification failed. Please try again.";
}
}
// If the Google Recaptcha box was not clicked
else {
echo "Please click the reCAPTCHA box.";
}
}
// If the form was not submitted
// Not a POST request, set a 403 (forbidden) response code.
else {
http_response_code(403);
echo "There was a problem with your submission, please try again.";
}
?>
I am fairly new to PHP. I have to send the form details to mail id. I browsed through The Internet and get the various link about the same. But I am facing the similar situation that when I am submitting my form filled with details then it is downloading the PHP file in the browser and main thing is I am not getting mail.
Here I pasting my code-
HTML file
<!DOCTYPE html>
<html lang="en">
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.0/jquery.min.js"></script>
<link rel="stylesheet" href="style.css">
</head>
<body>
<div id="page-wrapper">
<h1>AJAX Contact Form Demo</h1>
<div id="form-messages"></div>
<form id="ajax-contact" method="post" action="mailer.php">
<div class="field">
<label for="name">Name:</label>
<input type="text" id="name" name="name" required>
</div>
<div class="field">
<label for="email">Email:</label>
<input type="email" id="email" name="email" required>
</div>
<div class="field">
<label for="message">Message:</label>
<textarea id="message" name="message" required></textarea>
</div>
<div class="field">
<button type="submit">Send</button>
</div>
</form>
<script src="jquery-2.1.0.min.js"></script>
<script src="app.js"></script>
</body>
</html>
The mailer.php
<?php
// Only process POST reqeusts.
if ($_SERVER["REQUEST_METHOD"] == "POST") {
// Get the form fields and remove whitespace.
$name = strip_tags(trim($_POST["name"]));
$name = str_replace(array("\r","\n"),array(" "," "),$name);
$email = filter_var(trim($_POST["email"]), FILTER_SANITIZE_EMAIL);
$message = trim($_POST["message"]);
// Check that data was sent to the mailer.
if ( empty($name) OR empty($message) OR !filter_var($email, FILTER_VALIDATE_EMAIL)) {
// Set a 400 (bad request) response code and exit.
http_response_code(400);
echo "Oops! There was a problem with your submission. Please complete the form and try again.";
exit;
}
// Set the recipient email address.
//
$recipient = "shubhamvashishtha22#gmail.com";
// Set the email subject.
$subject = "New contact from $name";
// Build the email content.
$email_content = "Name: $name\n";
$email_content .= "Email: $email\n\n";
$email_content .= "Message:\n$message\n";
// Build the email headers.
$email_headers = "From: $name <$email>";
// Send the email.
if (mail($recipient, $subject, $email_content, $email_headers)) {
// Set a 200 (okay) response code.
http_response_code(200);
echo "Thank You! Your message has been sent.";
} else {
// Set a 500 (internal server error) response code.
http_response_code(500);
echo "Oops! Something went wrong and we couldn't send your message.";
}
} else {
// Not a POST request, set a 403 (forbidden) response code.
http_response_code(403);
echo "There was a problem with your submission, please try again.";
}
?>
My app.js file
$(function() {
// Get the form.
var form = $('#ajax-contact');
// Get the messages div.
var formMessages = $('#form-messages');
// TODO: The rest of the code will go here...
});
// Set up an event listener for the contact form.
$(form).submit(function(event) {
// Stop the browser from submitting the form.
event.preventDefault();
// TODO
});
// Serialize the form data.
var formData = $(form).serialize();
// Submit the form using AJAX.
$.ajax({
type: 'POST',
url: $(form).attr('action'),
data: formData
})
.done(function(response) {
// Make sure that the formMessages div has the 'success' class.
$(formMessages).removeClass('error');
$(formMessages).addClass('success');
// Set the message text.
$(formMessages).text(response);
// Clear the form.
$('#name').val('');
$('#email').val('');
$('#message').val('');
})
.fail(function(data) {
// Make sure that the formMessages div has the 'error' class.
$(formMessages).removeClass('success');
$(formMessages).addClass('error');
// Set the message text.
if (data.responseText !== '') {
$(formMessages).text(data.responseText);
} else {
$(formMessages).text('Oops! An error occured and your message could not be sent.');
}
});
Can anyone please suggest me how I can make this problem go. I am actually just copying it than also this is happening. Please help me?
It is possible that your server doesn't have a SMTP likesendmail or postfix enabled. You can run phpinfo() and look for this directive sendmail_path and see what is set.
You say that the PHP file is downloaded through the browser. This is not supposed to happen. When the server gets a request for a PHP file, it is meant to run the PHP code and only respond with the resulting HTML page. Visitors to your web page should never see any code, only the text and tags you choose to echo, which leads me to believe that your server may not actually be running PHP at the moment.
Is your PHP installation configured correctly, and is it running? If you are not configuring your own server, does your web host of choice have PHP listed as one of the languages it supports?
Your AJAX doesn't seem to do anything other than telling the form to submit, so I don't think it's the problem, but for the sake of isolating the issue: What happens if you comment out the jQuery and AJAX script tags and just use a regular HTML form to POST to mailer.php?
Got contact form like this (JSFiddle).
Registered captcha. How to implement the correct integration on the client and server?
In the form inserted just a div. Submit gonna work like this? How to connect submit and captcha?
It refers to the POST request:
How does it send?
There is PHP:
<?php
// Only process POST reqeusts.
if ($_SERVER["REQUEST_METHOD"] == "POST") {
// Get the form fields and remove whitespace.
$name = strip_tags(trim($_POST["name"]));
$name = str_replace(array("\r","\n"),array(" "," "),$name);
$email = filter_var(trim($_POST["email"]), FILTER_SANITIZE_EMAIL);
$message = trim($_POST["message"]);
// Check that data was sent to the mailer.
if ( empty($name) OR empty($message) OR !filter_var($email, FILTER_VALIDATE_EMAIL)) {
// Set a 400 (bad request) response code and exit.
http_response_code(400);
echo "Oops! There was a problem with your submission. Please complete the form and try again.";
exit;
}
// Set the recipient email address.
$recipient = "mail#mail.com";
// Set the email subject.
$subject = "New contact from $name";
// Build the email content.
$email_content = "Name: $name\n";
$email_content .= "Email: $email\n\n";
$email_content .= "Message:\n$message\n";
// Build the email headers.
$email_headers = "From: $name <$email>";
// Send the email.
if (mail($recipient, $subject, $email_content, $email_headers)) {
// Set a 200 (okay) response code.
http_response_code(200);
echo "Thank You! Your message has been sent.";
} else {
// Set a 500 (internal server error) response code.
http_response_code(500);
echo "Oops! Something went wrong and we couldn't send your message.";
}
} else {
// Not a POST request, set a 403 (forbidden) response code.
http_response_code(403);
echo "There was a problem with your submission, please try again.";
}
I have integrated the google reCaptcha in our website. Here is our implementation.
Front-end Code:
<script src="https://www.google.com/recaptcha/api.js?onload=recaptchaCallBack&render=explicit" async defer></script>
<script type="text/javascript">
var recaptcha_sponsorship_signup_form;
var recaptchaCallBack = function() {
// Render the recaptcha on the element with ID "recaptcha_sponsorship_signup_form"
recaptcha_sponsorship_signup_form = grecaptcha.render('recaptcha_sponsorship_signup_form', {
'sitekey' : 'your_recaptcha_website_key',
'theme' : 'light'
});
};
</script>
<dt>Prove you’re not a robot</dt>
<dd style="height: 78px;">
<div id="recaptcha_sponsorship_signup_form"></div>
</dd>
Server Side Code:
$fileContent = '';
if (isset($_REQUEST['g-recaptcha-response']) && !empty($_REQUEST['g-recaptcha-response'])) {
$fileContent = file_get_contents("https://www.google.com/recaptcha/api/siteverify?secret=your_recaptcha_secret_key&response=". $_REQUEST['g-recaptcha-response']);
}
$jsonArray = json_decode($fileContent, true);
if (isset($jsonArray['success']) && $jsonArray['success']==true) {
// process your logic here
} else {
echo "Invalid verification code, please try again!";
}
You can use this library ;
https://github.com/google/recaptcha/blob/master/examples/example-captcha.php
First, register keys for your site at https://www.google.com/recaptcha/admin
When your app receives a form submission containing the g-recaptcha-response field, you can verify it using:
<?php
$recaptcha = new \ReCaptcha\ReCaptcha($secret);
$resp = $recaptcha->verify($gRecaptchaResponse, $remoteIp);
if ($resp->isSuccess()) {
// verified!
} else {
$errors = $resp->getErrorCodes();
}
You can see an end-to-end working example in examples/example-captcha.php
Ok I create an ajax form by following a tutorial. Everything is working fine. But my form fields are not clearing after submission. I searched here & found some solution, but not working for me. I've tried:
number 1: $('form#contactform input[type="text"],texatrea, select').val('');
number 2: $("#name").val("");
$("#email").val("");
$("#phone").val("");
number 3: $('#contactform')[0].reset();
but this solutions are not working for me.
My html:
<div id="form-messages"></div>
<form method="post" action="mailer.php" name="contactform" id="contactform">
<fieldset>
<div class="col-sm-3 col-xs-6">
<!-- Name -->
<input name="name" type="text" id="name" size="30" placeholder="Name" value="" />
</div>
<div class="col-sm-3 col-xs-6">
<!-- Email -->
<input name="email" type="text" id="email" size="30" placeholder="Email" value="" />
</div>
<div class="col-sm-3 col-xs-6">
<!-- Phone -->
<input name="phone" type="text" id="phone" size="30" placeholder="Phone" value="" />
</div>
<div class="col-sm-3 col-xs-12">
<!-- Send button -->
<input type="submit" class="submit" id="submit" value="Send message" />
</div>
</fieldset>
</form>
My js:
$(function() {
// Get the form.
var form = $('#contactform');
// Get the messages div.
var formMessages = $('#form-messages');
// Set up an event listener for the contact form.
$(form).submit(function(e) {
// Stop the browser from submitting the form.
e.preventDefault();
// Serialize the form data.
var formData = $(form).serialize();
// Submit the form using AJAX.
$.ajax({
type: 'POST',
url: $(form).attr('action'),
data: formData
})
.done(function(response) {
// Make sure that the formMessages div has the 'success' class.
$(formMessages).removeClass('error');
$(formMessages).addClass('success');
// Clear the form.
$('form#contactform input[type="text"],texatrea, select').val('');
// Set the message text.
$(formMessages).text(response);
})
.fail(function(data) {
// Make sure that the formMessages div has the 'error' class.
$(formMessages).removeClass('success');
$(formMessages).addClass('error');
// Set the message text.
if (data.responseText !== '') {
$(formMessages).text(data.responseText);
} else {
$(formMessages).text('Oops! An error occured and your message could not be sent.');
}
});
});
});
& My Php
<?php
// Only process POST reqeusts.
if ($_SERVER["REQUEST_METHOD"] == "POST") {
// Get the form fields and remove whitespace.
$name = strip_tags(trim($_POST["name"]));
$name = str_replace(array("\r","\n"),array(" "," "),$name);
$email = filter_var(trim($_POST["email"]), FILTER_SANITIZE_EMAIL);
$phone = strip_tags(trim($_POST["phone"]));
$phone = str_replace(array("\r","\n"),array(" "," "),$phone);
// Check that data was sent to the mailer.
if ( empty($name) OR empty($phone) OR !filter_var($email, FILTER_VALIDATE_EMAIL)) {
// Set a 400 (bad request) response code and exit.
http_response_code(400);
echo "Oops! There was a problem with your submission. Please complete the form and try again.";
exit;
}
// Set the recipient email address.
// FIXME: Update this to your desired email address.
$recipient = "friday#imransdesign.com";
// Set the email subject.
$subject = "New contact from $name";
// Build the email content.
$email_content = "Name: $name\n";
$email_content .= "Email: $email\n";
$email_content .= "Phone: $phone\n";
// Build the email headers.
$email_headers = "From: $name <$email>";
// Send the email.
if (mail($recipient, $subject, $email_content, $email_headers)) {
// Set a 200 (okay) response code.
header("HTTP/1.0 404 Not Found");
echo "Thank You! Your message has been sent.";
$_POST=array();
} else {
// Set a 500 (internal server error) response code.
header("HTTP/1.0 404 Not Found");
echo "Oops! Something went wrong and we couldn't send your message.";
}
} else {
// Not a POST request, set a 403 (forbidden) response code.
header("HTTP/1.0 404 Not Found");
echo "There was a problem with your submission, please try again.";
}
?>
What should I do?
live example: http://imransdesign.com/ajax-form/
Your selector for number 1 is wrong. It should be:
$('#contactform').find('input[type="text"], texatrea, select').val('');
I don't know about number 2 and number 3. May be you have duplicate IDs in your page ... let me take a look. Your IDs are good. Something else must be going on.
I tested number two and three in the dev tools console on your page and they work fine:
$('#contactform')[0].reset(); //cleared the whole form
$('#name').val(''); // Cleared the name field.
There seems to be a problem with your server. It's returning a 400/404 --- fail and since you do not clear your form in the .fail callback, your form would not be cleared. The .done callback is not being called:
mailer.php POST 400 text/html jquery-2.1.0.min.js:4 279 B 378 ms
mailer.php POST 400 text/html jquery-2.1.0.min.js:4 279 B 339 ms
mailer.php POST 404 text/html jquery-2.1.0.min.js:4 256 B 343 ms
Somehow the server returns Thank You! Your message has been sent. which is output by the following part in .fail():
if (data.responseText !== '') {
$(formMessages).text(data.responseText);
} else {
Try
$('#contactform fieldset div input').val('');
instead of
$('form#contactform input[type="text"],texatrea, select').val('');
I think you need this to clear all input fields inside form tag use this
$("#formid").find('input, textarea').not(":submit").val('');
This FIDDLE will clear all the input fields and textarea inside the form tag on submitting .. change it as you want ..its just example
Just do this:
.done(function(response) {
...
contactform.reset();
}