I have minimal knowledge in php and js. Im trying to get value from my form once submit button has been click then trigger my php script.
Js file:
document.getElementById('form')
.addEventListener('submit', function (event) {
event.preventDefault();
let response = grecaptcha.getResponse();
if (validateFields() && !response.length == 0) {
console.log('got here');
var data = new FormData(document.getElementById('form'));
var xhr = new XMLHttpRequest();
xhr.open('POST', 'form-to-email.php');
xhr.onload = function () {
console.log(this.response);
};
xhr.send(data);
return false;
}
document.getElementById('button').style.cursor = 'not-allowed';
});
Here's my php script:
<?php
// Google reCAPTCHA API key configuration
$siteKey = 'siteKey';
$secretKey = 'secretKey';
if (isset($_REQUEST['submit'])) {
$to = "[email protected]"; // this is your Email address
$from = $_POST['email']; // this is the sender's Email address
$name = $_POST['name'];
$subject = "Form submission";
$message = $name . " wrote the following:" . "\n\n" . $_POST['message'];
if (isset($_POST['g-recaptcha-response']) && !empty($_POST['g-recaptcha-response'])) {
// Verify the reCAPTCHA response
$verifyResponse = file_get_contents('https://www.google.com/recaptcha/api/siteverify?secret=' . $secretKey . '&response=' . $_POST['g-recaptcha-response']);
// Decode json data
$responseData = json_decode($verifyResponse);
// If reCAPTCHA response is valid
if ($responseData->success) {
$headers = "From:" . $name . '<' . $from . '>' . PHP_EOL;
$headers .= "Reply-To:" . $to . PHP_EOL;
$headers .= "MIME-Version 1.0" . PHP_EOL;
$headers .= "Content-Type: text/html; charset=UTF-8" . PHP_EOL;
$headers .= "X-Mailer: PHP/" . phpversion();
$status = mail($to, $subject, $message, $headers);
echo "<pre>";
var_dump($status);
if ($status) {
echo '<p>Your message has been sent. We will get in touch with you soon. Thank you!</p>';
} else {
echo '<p>Something went wrong. Please try again!</p>';
}
} else {
echo 'error';
}
} else {
echo 'Please check on the reCAPTCHA box.';
}
}
?>
Here's my form code in index.php. I have 3 fields name, email and message:
<?php include_once 'form-to-email.php';?>
<form id="form" method="post" action="">
<div >
<input type="text" id="name" name="name" placeholder="Your Name">
<span id="invalid-name">
Please enter at least 2 chars
</span>
</div>
<div >
<input id="email" type="email" name="email" placeholder="Email Address">
<span id="invalid-email">
Please enter valid email
</span>
</div>
<div >
<textarea id="message" name="message" placeholder="Message">
</textarea>
<span id="invalid-message">
Please write something for us
</span>
</div>
<div data-sitekey="<?php echo $siteKey; ?>">
</div>
<input type="submit" name="submit" id="button" value="Book a Demo">
</form>
I get console.log empty values. Is this the right path or calling php is simply not doable?
Update
It now echos true and message sent.
CodePudding user response:
Based on your question you are looking simply to submit a form and access the value in your php script. But it seems you are trying to submit the form via an ajax request. The first place to start is in your javascript code. The first thing I see is that you are calling a couple functions that are not defined so you never pass the if check and get to where it is supposed to say 'got here':
let response = grecaptcha.getResponse();
if (validateFields() && !response.length == 0) {
console.log('got here'); // you never get to this point
grecaptcha
is not yet defined and I don't see any function definition for validateFields()
so that fails as well. As a temporary fix while you are debugging it, comment out the if
check like this so you can focus on the xhr
request:
document.getElementById('form')
.addEventListener('submit', function (event) {
event.preventDefault();
// Comment out the following two lines
// so you can focus on getting the XHR request to work
// let response = grecaptcha.getResponse();
// if (validateFields() && !response.length == 0) {
console.log('got here');
var data = new FormData(document.getElementById('form'));
var xhr = new XMLHttpRequest();
xhr.open('POST', 'form-to-email.php');
xhr.onload = function () {
console.log(this.response);
};
xhr.send(data);
return false;
// } Comment out the closing bracket to match the comments from above
document.getElementById('button').style.cursor = 'not-allowed';
});
Ok, now when you hit submit, you should be sending the form data to your php script. To test out what shows up in the php script you can bail out early to see the contents of your $_POST variable.
<?php
// Google reCAPTCHA API key configuration
$siteKey = 'siteKey';
$secretKey = 'secretKey';
// Echo out the word success to make sure you got to this point.
// Then echo out the contents of your $_POST variable to see what is in it.
echo "Success";
var_dump($_POST);
exit; // exiting here bails out early.
// When you var_dump out your $_POST variable you will notice that
// $_POST['submit'] is not set since you don't have an input field
// for that value.
if (isset($_POST['submit'])) {
$to = "[email protected]"; // this is your Email address
$from = $_POST['email']; // this is the sender's Email address
$name = $_POST['name'];
$subject = "Form submission";
$message = $name . " wrote the following:" . "\n\n" . $_POST['message'];
. . .
Now, since you decided to do this via ajax, it will be a bit trickier to see the echo statement and the var_dump. To find out if it is working you need to use your dev tools network tab (F12 -> Network). Under the network tab you will see something like this: Each time you hit submit, it should show a new line representing that request to the server. You can select a line and inspect the payload, preview, response tabs to see what was sent and what was received.
I hope this helps point you in the right direction. I'm not going to get into the issues with validating re-captcha and form validation. Those are topics for another question once you get the basic form working.
Cheers!
CodePudding user response:
Based on this answer, change the way you're calling the php function.
document.getElementById('form')
.addEventListener('submit', function (event) {
event.preventDefault();
let response = grecaptcha.getResponse();
if (validateFields() && !response.length == 0) {
var data = new FormData(document.getElementById('form'));
var xhr = new XMLHttpRequest();
xhr.onreadystatechange = function() {
if(xhr.readyState == 4 && xhr.status == 200) {
console.log(xhr.responseText);
}
}
xhr.open('POST', 'form-to-email.php?submit'); //don't forget submit here
xhr.send(data);
}
document.getElementById('button').style.cursor = 'not-allowed';
});
Also, try using $_REQUEST
instead of $_POST
in PHP file, as in:
if (isset($_REQUEST['submit'])) {
echo 'HERE IN PHP';
}