How do you clear form field after submit/success? - php

I'm working with this exact same MailChimp PHP/AJAX subscribe processing form - clear text value after success? - but I am absolutely stumped on how to actually get the form field to cleat after success.
Apparently to what Felix recommended here - clear text value after success? - the code works only if the span element exists at document load, and you have to call the if-statement after completion if using Ajax.
Could someone please help me? How do you clear the form field after it has been successfully completed by a user?
Here is the code:
<?php
// store-address.php
function storeAddress(){
// Validation
if(!$_GET['email']){ return "No email address provided"; }
if(!preg_match("/^[_a-z0-9-]+(\.[_a-z0-9-]+)*#[a-z0-9-]+(\.[a-z0-9-]+)*$/i", $_GET['email'])) {
return "Email address is invalid";
}
require_once('MCAPI.class.php');
// grab an API Key from http://admin.mailchimp.com/account/api/
$api = new MCAPI('my-api-key');
// grab your List's Unique Id by going to http://admin.mailchimp.com/lists/
// Click the "settings" link for the list - the Unique Id is at the bottom of that page.
$list_id = "my-list";
if($api->listSubscribe($list_id, $_GET['email'], '') === true) {
// It worked!
return 'Success! Check your email to confirm sign up.';
}else{
// An error ocurred, return error message
return 'Error: ' . $api->errorMessage;
}
}
// If being called via ajax, autorun the function
if($_GET['ajax']){ echo storeAddress(); }
?>
The form code:
<form action="<?=$_SERVER['PHP_SELF']; ?>" id="signup" class="subscribe" method="get">
<fieldset>
<input type="text" id="email" name="email" placeholder="your email address" />
<input type="submit" name="submit" value="Send it" />
</fieldset>
</form>
<p id="response"><? require_once('inc/store-address.php'); if($_GET['submit']){ echo storeAddress(); } ?></p>
<script type="text/javascript" src="/js/prototype.js"></script>
<script type="text/javascript" src="/js/mailing-list.js"></script>
The mailing-list javascript code:
// Load Events Listeners
Event.observe(window, 'load', init, false);
function init(){
Event.observe('signup','submit',storeAddress);
}
// AJAX call sending sign up info to store-address.php
function storeAddress(event) {
// Update user interface
$('response').innerHTML = 'Getting email address...';
// Prepare query string and send AJAX request
var pars = 'ajax=true&email=' + escape($F('email'));
var myAjax = new Ajax.Updater('response', 'inc/store-address.php', {method: 'get', parameters: pars});
Event.stop(event); // Stop form from submitting when JS is enabled
}

There are two solutions to this.
The less elegant one would be to create a JS function the resets every form field value manually.
The better way would be to store a hidden reset input in your form with an ID:
<input type="reset" id="blagh" style="display:none"/>
And simply 'click' it using jQuery:
$('#blagh').click();

The jquery form plugin has resetForm(). Just sayin'.

Related

How to Verify Google Recaptcha V3 Response?

How to integrate Google reCAPTCHA Version 3 in Client Side and Server Side(php). following code use to display recaptcha but its not working good. How to do this integration.
<html>
<head>
<script src='https://www.google.com/recaptcha/api.js?render=XXXX-XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX'></script>
</head>
<body>
<script>
grecaptcha.ready(function() {
grecaptcha.execute('XXXX-XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX', {
action: 'action_name'
});
});
</script>
<form action="verify.php" method="post">
<input type="text" name="name" placeholder="Your name" required>
<input type="email" name="email" placeholder="Your email address" required>
<textarea name="message" placeholder="Type your message here...." required></textarea>
<input type="submit" name="submit" value="SUBMIT">
</form>
</body>
</html>
Verify.php
<?php
if(isset($_POST['g-recaptcha-response']) && !empty($_POST['g-recaptcha-response'])) {
//your site secret key
$secret = 'XXXX-XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX';
//get verify response data
$verifyResponse = file_get_contents('https://www.google.com/recaptcha/api/siteverify?secret='.$secret.'&response='.$_POST['g-recaptcha-response']);
$responseData = json_decode($verifyResponse);
if($responseData->success):
print_r("Working Fine"); exit;
else:
print_r("No valid Key"); exit;
endif;
} else {
print_r("Not Working Captcha"); exit;
}
?>
A simple example of a contact form verified by Google reCAPTCHA v3 with pure JavaScript and PHP
tldr; skip to code at the bottom.
Relevant reCAPTCHA docs etc:
Create keys: https://www.google.com/recaptcha/admin/create
Frontend integration: https://developers.google.com/recaptcha/docs/v3
Backend verification: https://developers.google.com/recaptcha/docs/verify
(If Google are listening, we love your work and it would be wonderful to have some more elaborate examples linked to the above pages please.)
Overview:
Get keys from Google
Load recaptcha/api.js in head of html
Hijack form submission with JavaScript and at that point get token from Google
Submit form with token to your server
Make request from your website's backend to Google to verify the
form submission
Interpret the response and proceed as necessary
Important to note: the 'success' response parameter indicates only whether or not the captcha was evaluated successfully, it doesn't indicate whether the submission was likely to be spam or not.
The 'score' parameter is the result you need to know about. The higher the score (a number between 0 and 1) the more likely a submission is genuine, and it's upto you what threshold (e.g. 0.5) to accept.
In detail:
Add the following line to the head of your HTML to load the recaptcha api.js code:
<script src="https://www.google.com/recaptcha/api.js?render=$reCAPTCHA_site_key"></script>
(where $reCAPTCHA_site_key is your public 'site key', which I've saved in a 'config.php' file.)
You need to submit a token (received from Google & unique to each form submission) to your server. I think it's simplest to send it via POST along with the rest of the form data. To that end I include a hidden field in the form as follows:
<form id="contactForm" method="post" action="contact">
<!-- other form inputs -->
<input type="hidden" id="gRecaptchaResponse" name="gRecaptchaResponse">
<input type="submit" name="contact_submit" value="Send message">
</form>
(Nb. "contact" is contact.php, but I've 'rewritten' the url with .htaccess)
Now we need to hijack the default form submission to generate the token. We could generate the token on page load but since the token is only valid for two minutes (if I'm reading the https://developers.google.com/recaptcha/docs/verify page correctly) I think it's better to fetch it at the point of needing to send it to your site's server.
To this end I added the following right after the closing form tag:
<script>
contactForm.addEventListener('submit', event => {
event.preventDefault()
validate(contactForm)
});
</script>
I've put the validate(form) function just before the closing body tag:
function validate(form) {
//perform optional error checking on form. If no errors then request a token and put it into the hidden field
getRecaptchaToken(form)
}
//some other (optional) form validation functions
function getRecaptchaToken(form) {
grecaptcha.ready(function() {
grecaptcha.execute($reCAPTCHA_site_key, {action: 'contactForm'}).then(function(token) {
gRecaptchaResponse.value = token //set the value of the hidden field
form.submit() //submit the form
});
});
}
Notes:
$reCAPTCHA_site_key is your public Site Key
action: 'contactForm' identifies the submission of this particular
form in the Google reCAPTCHA dashboard, and confirming it is as expected in the backend is a recommended extra
security step
In the main PHP file, when the form submission is received:
//get the IP address of the origin of the submission
$ip = $_SERVER['REMOTE_ADDR'];
//construct the url to send your private Secret Key, token and (optionally) IP address of the form submitter to Google to get a spam rating for the submission (I've saved '$reCAPTCHA_secret_key' in config.php)
$url = 'https://www.google.com/recaptcha/api/siteverify?secret=' . urlencode($reCAPTCHA_secret_key) . '&response=' . urlencode($g_recaptcha_response) . '&remoteip=' . urlencode($ip);
//save the response, e.g. print_r($response) prints { "success": true, "challenge_ts": "2019-07-24T11:19:07Z", "hostname": "your-website-domain.co.uk", "score": 0.9, "action": "contactForm" }
$response = file_get_contents($url);
//decode the response, e.g. print_r($responseKeys) prints Array ( [success] => 1 [challenge_ts] => 2019-07-24T11:19:07Z [hostname] => your-website-domain.co.uk [score] => 0.9 [action] => contactForm )
$responseKeys = json_decode($response, true);
//check if the test was done OK, if the action name is correct and if the score is above your chosen threshold (again, I've saved '$g_recaptcha_allowable_score' in config.php)
if ($responseKeys["success"] && $responseKeys["action"] == 'contactForm') {
if ($responseKeys["score"] >= $g_recaptcha_allowable_score) {
//send email with contact form submission data to site owner/ submit to database/ etc
//redirect to confirmation page or whatever you need to do
} elseif ($responseKeys["score"] < $g_recaptcha_allowable_score) {
//failed spam test. Offer the visitor the option to try again or use an alternative method of contact.
}
} elseif($responseKeys["error-codes"]) { //optional
//handle errors. See notes below for possible error codes
//personally I'm probably going to handle errors in much the same way by sending myself a the error code for debugging and offering the visitor the option to try again or use an alternative method of contact
} else {
//unkown screw up. Again, offer the visitor the option to try again or use an alternative method of contact.
}
Notes:
This is is the data which will be in the response from Google
(returned as a JSON object):
{
"success": true|false, // whether this request was a valid reCAPTCHA token for your site
"score": number // the score for this request (0.0 - 1.0)
"action": string // the action name for this request (important to verify)
"challenge_ts": timestamp, // timestamp of the challenge load (ISO format yyyy-MM-dd'T'HH:mm:ssZZ)
"hostname": string, // the hostname of the site where the reCAPTCHA was solved
"error-codes": [...] // optional
}
These are the possible error codes:
missing-input-secret: The secret parameter is missing.
invalid-input-secret: The secret parameter is invalid or malformed.
missing-input-response: The response parameter is missing.
invalid-input-response: The response parameter is invalid or malformed.
bad-request: The request is invalid or malformed.
timeout-or-duplicate: The response is no longer valid; either is too
old or has been used previously.
Putting it all together:
contact.php
<?php //contact.php
require_once('config.php');
//do server-side validation of other form fields
if (/*form has been submitted and has passed server-side validation of the other form fields*/) {
$ip = $_SERVER['REMOTE_ADDR'];
$url = 'https://www.google.com/recaptcha/api/siteverify?secret=' . urlencode($reCAPTCHA_secret_key) . '&response=' . urlencode($g_recaptcha_response) . '&remoteip=' . urlencode($ip);
$response = file_get_contents($url);
$responseKeys = json_decode($response, true);
if ($responseKeys["success"] && $responseKeys["action"] == 'contactForm') {
if ($responseKeys["score"] >= $g_recaptcha_allowable_score) {
//send email with contact form submission data to site owner/ submit to database/ etc
//redirect to confirmation page or whatever you need to do
} elseif ($responseKeys["score"] < $g_recaptcha_allowable_score) {
//failed spam test. Offer the visitor the option to try again or use an alternative method of contact.
}
} elseif($responseKeys["error-codes"]) { //optional
//handle errors. See notes below for possible error codes
//(I handle errors by sending myself an email with the error code for debugging and offering the visitor the option to try again or use an alternative method of contact)
} else {
//unkown screw up. Again, offer the visitor the option to try again or use an alternative method of contact.
}
exit;
} else { //(re)display the page with the form
echo <<<_END
<!DOCTYPE html>
<html lang="en">
<head>
<title>Contact | Your website</title>
<link rel="stylesheet" href="css/style.css">
<script src="https://www.google.com/recaptcha/api.js?render=$reCAPTCHA_site_key"></script>
</head>
<body>
<!-- header etc -->
<form id="contactForm" method="post" action="contact">
//other form inputs
<input type="hidden" id="gRecaptchaResponse" name="gRecaptchaResponse">
<input type="submit" name="contact_submit" value="Send message">
</form>
<script>
contactForm.addEventListener('submit', event => {
event.preventDefault()
validate(contactForm)
});
</script>
<!-- footer etc -->
<script>
function validate(form) {
//perform optional client-side error checking of the form. If no errors are found then request a token and put it into the hidden field. Finally submit the form.
getRecaptchaToken(form)
}
//some (optional) form field validation functions
function getRecaptchaToken(form) {
grecaptcha.ready(function() {
grecaptcha.execute($reCAPTCHA_site_key, {action: 'contactForm'}).then(function(token) {
gRecaptchaResponse.value = token
form.submit()
});
});
}
</script>
</body>
</html>
_END;
config.php
<?php //config.php
//other site settings
// Google reCAPTCHA v3 keys
// For reducing spam contact form submissions
// Site key (public)
$reCAPTCHA_site_key = 'N0t-a-real-0N3_JHbnbUJ-BLAHBLAH_Blahblah';
// Secret key
$reCAPTCHA_secret_key = 'N0t-a-real-0N3_i77tyYGH7Ty6UfG-blah';
// Min score returned from reCAPTCHA to allow form submission
$g_recaptcha_allowable_score = 0.5; //Number between 0 and 1. You choose this. Setting a number closer to 0 will let through more spam, closer to 1 and you may start to block valid submissions.
Try this.
<script>
grecaptcha.ready(function() {
grecaptcha.execute('YOUR_SITE_KEY', {action: 'MyForm'})
.then(function(token) {
console.log(token)
document.getElementById('g-recaptcha-response').value = token;
});
});
</script>
<form action="verify.php" method="post">
<input type="hidden" id="g-recaptcha-response" name="g-recaptcha-response">
<input type="text" name="name" placeholder="Your name" required >
<input type="email" name="email" placeholder="Your email address" required>
<input type="submit" name="submit" value="SUBMIT" >
</form>
<html>
<head>
<script src='https://www.google.com/recaptcha/api.js?render=6Le7-FkUAAAAADDSsTVBvpoUB5MkesNKgPVemFf-UD'></script>
</head>
<body>
<script>
// when form is submit
$('form').submit(function() {
// we stoped it
event.preventDefault();
// needs for recaptacha ready
grecaptcha.ready(function() {
// do request for recaptcha token
// response is promise with passed token
grecaptcha.execute('6Le7-FkUAAAAADDSsTVBvpoUB5MkesNKgPVemFf-UD', {action: 'create_comment'}).then(function(token) {
// add token to form
$('form').prepend('<input type="hidden" name="token" value="' + token + '">');
$('form').prepend('<input type="hidden" name="action" value="create_comment">');
// submit form now
$('form').unbind('submit').submit();
});;
});
});
</script>
<form action="verify.php" method="post">
<input type="text" name="name" placeholder="Your name" required >
<input type="email" name="email" placeholder="Your email address" required>
<textarea name="message" placeholder="Type your message here...." required></textarea>
<input type="submit" name="submit" value="SUBMIT">
</form>
</body>
</html>
php
$token = $_POST['token'];
$secret = 'ur secret';
$action = $_POST['action'];
// now you need do a POST requst to google recaptcha server.
// url: https://www.google.com/recaptcha/api/siteverify.
// with data secret:$secret and response:$token
At this point in the code, you will need to do a post request to ReCAPTCHA to verify the token, as documented here: https://www.google.com/recaptcha/api/siteverify. The response will be a json object with field "success" (true/false) and "action"
for comparison (==) and score (number from 0.0 - 1.0)
https://developers.google.com/recaptcha/docs/v3#api-response.
You can also specify action name for each request (create_post, update_post, create_comment ...)
Here is a sample working code with the demo.
html side code
<html>
<head>
<title>Google recapcha v3 demo - Codeforgeek</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://www.google.com/recaptcha/api.js?render=put your site key here"></script>
</head>
<body>
<h1>Google reCAPTHA Demo</h1>
<form id="comment_form" action="form.php" method="post" >
<input type="email" name="email" placeholder="Type your email" size="40"><br><br>
<textarea name="comment" rows="8" cols="39"></textarea><br><br>
<input type="submit" name="submit" value="Post comment"><br><br>
</form>
<script>
// when form is submit
$('#comment_form').submit(function() {
// we stoped it
event.preventDefault();
var email = $('#email').val();
var comment = $("#comment").val();
// needs for recaptacha ready
grecaptcha.ready(function() {
// do request for recaptcha token
// response is promise with passed token
grecaptcha.execute('put your site key here', {action: 'create_comment'}).then(function(token) {
// add token to form
$('#comment_form').prepend('<input type="hidden" name="g-recaptcha-response" value="' + token + '">');
$.post("form.php",{email: email, comment: comment, token: token}, function(result) {
console.log(result);
if(result.success) {
alert('Thanks for posting comment.')
} else {
alert('You are spammer ! Get the #$%K out.')
}
});
});;
});
});
</script>
</body>
</html>
PHP code.
<?php
$email;$comment;$captcha;
if(isset($_POST['email'])){
$email=$_POST['email'];
}if(isset($_POST['comment'])){
$comment=$_POST['comment'];
}if(isset($_POST['token'])){
$captcha=$_POST['token'];
}
if(!$captcha){
echo '<h2>Please check the the captcha form.</h2>';
exit;
}
$secretKey = "put your secret key here";
$ip = $_SERVER['REMOTE_ADDR'];
// post request to server
$url = 'https://www.google.com/recaptcha/api/siteverify?secret=' . urlencode($secretKey) . '&response=' . urlencode($captcha);
$response = file_get_contents($url);
$responseKeys = json_decode($response,true);
header('Content-type: application/json');
if($responseKeys["success"]) {
echo json_encode(array('success' => 'true'));
} else {
echo json_encode(array('success' => 'false'));
}
?>
Its working fine.
Demo: https://demo.codeforgeek.com/recaptcha-v3/
tutorial: https://codeforgeek.com/2019/02/google-recaptcha-v3-tutorial/
I'd like to give you a complete workflow to integrate recaptchav3 into an ASP.NET core MVC solution.
in your appsettings.json file:
"RecaptchaSettings": {
"Uri": "https://www.google.com/recaptcha/api/siteverify",
"SecretKey": "your private key"
"SiteKey": "your public key",
"Version": "v3"
}
in your view (#razor syntax):
#using Microsoft.Extensions.Configuration
#inject IConfiguration Configuration
<script src="https://www.google.com/recaptcha/api.js?render=#Configuration.GetSection("RecaptchaSettings")["SiteKey"]"></script>
<script>
grecaptcha.ready(function () {
grecaptcha.execute('#Configuration.GetSection("RecaptchaSettings")["SiteKey"]', { action: 'homepage' })
.then(function (token) {
document.getElementById('g-recaptcha-response').value = token;
});
});
</script>
and in your form put this:
<form action="/">
…
<input type="hidden" id="g-recaptcha-response" name="g-recaptcha-response">
…
</form>
I create a simple method to manage it:
public async Task<bool> ChallengePassed(string uri, string gRecaptchaResponse, string secret)
{
var concUri = uri + "?secret=" + secret + "&response=" + gRecaptchaResponse;
var request = new HttpRequestMessage(HttpMethod.Get, concUri);
var res = await _Client.SendAsync(request);
if (!res.IsSuccessStatusCode)
{
return false;
}
var data = await res.Content.ReadAsStringAsync();
dynamic JSONdata = JObject.Parse(data);
if (JSONdata.success != "true")
{
return false;
}
return true;
}
#endregion
#region PRIVATE
#endregion
#endregion
#endregion
}
and simply I called it into a Controller:
//recaptcha validation
bool isChallengeOk = await _CaptchaVerify.ChallengePassed(_Configuration.GetValue<string>("RecaptchaSettings:Uri"), Request.Form["g-recaptcha-response"], _Configuration.GetValue<string>("RecaptchaSettings:SecretKey"));
notice that I'm setting the input parameters from the "_Configuration" object, that represents an instance of configuration setting object in Startup.cs. You can pass manually input parameters to the method.
Enjoy it

How to get response from ajax after selecting the auto completing email

I have a code to check email id is available or not in the database using ajax on keypress. If email Id is available then submit button will enable or email id is not available in the database then submit button will show disabled.
I have no issue in above process below code is working for above process.
My issue is some time users are getting the popup to store the username and password in the browser when the user entered the username and password. I am talking about cookies or can say auto-filed data. For example: If you enter the email id two or three times in text field then next time you clicked on the field you will automatically get your email.
Same issue I am getting. I saved the username and password on my browser and now I am selecting my username and clicking the button which is not working because I am using ajax on keypress. I f I type the email then it is working If I select the email then not working. I need if any user selects the email id than also button should active.
Hope you understand my issue .would you help me in this issue?
On keypress Getting ajax response
Auto filling the email the no response from ajax
<!DOCTYPE html>
<html>
<head>
<title></title>
</head>
<body>
<form action="" method="POST">
<input type="email" id="email" name="email" class="text_field" />
<span id="email-validation-error" class="error"></span>
<input id="submitYesNo" type="submit" name="next" value="submit" disabled="disabled">
</form>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script type="text/javascript">
/*checking email id is already exist or not*/
$(document).ready(function() {
$('input[type="submit"]').attr('disabled', true);
});
$(document).ready(function()
{
var elem = $("#id"); //assign target element with id
$("input[name='email']").on('keyup',function()
{
var email = $('#email').val();
$.ajax(
{
url:'process.php',
type:'POST',
data:'email='+email,
success:function(data)
{
if (data == "success") {
$("#submitYesNo").prop('disabled', false);
$("#email-validation-error").html(data);
}
else{
$("#email-validation-error").html(data);
$("#submitYesNo").prop('disabled', true);
}
},
});
});
});
</script>
</body>
</html>
PHP
if(isset($_POST['email'])){
$email=$_POST['email'];
$_SESSION['username']=$email;
$query="SELECT Email FROM `request` WHERE Email='".$email."'";
$result = $conn->query($query);
$search_record=$result->num_rows;
if ($search_record > 0) {
echo "success";
}
else{
echo "Email does not exist, please sign up to use our services";
}
}
This function will work when the user click or focus outside of that input field otherwise it wont work
$("input[name='email']").bind('change keyup', function(){
console.log(this.value);
});
Check this once it may help on your scenario
Bind blur event with keyup event.So that when your textbox loose focus at that time your ajax can be called again
$("input[name='email']").on('keyup blur',function() // Add blur event
{

Hiding a form upon click of the submission button

<?php
'<form method="post" action="postnotice.php");>
<p> <label for="idCode">ID Code (required): </label>
<input type="text" name="idCode" id="idCode"></p>
<p> <input type="submit" value="Post Notice"></p>
</form>'
?>
Alright, so that's part of my php form - very simple. For my second form (postnotice.php):
<?php
//Some other code containing the password..etc for the connection to the database.
$conn = #mysqli_connect($sql_host,$sql_user,$sql_pass,$sql_db);
if (!$conn) {
echo "<font color='red'>Database connection failure</font><br>";
}else{
//Code to verify my form data/add it to the database.
}
?>
I was wondering if you guys know of a simple way - I'm still quite new to php - that I could use to perhaps hide the form and replace it with a simple text "Attempting to connect to database" until the form hears back from the database and proceeds to the next page where I have other code to show the result of the query and verification of "idCode" validity. Or even database connection failure. I feel it wrong to leave a user sitting there unsure if his/her button click was successful while it tries to connect to the database, or waits for time out.
Thanks for any ideas in advance,
Luke.
Edit: To clarify what I'm after here was a php solution - without the use of ajax or javascript (I've seen methods using these already online, so I'm trying to look for additional routes)
what you need to do is give form a div and then simply submit the form through ajax and then hide the div and show the message after you get the data from server.
<div id = "form_div">
'<form method="post" id = "form" action="postnotice.php";>
<p> <label for="idCode">ID Code (required): </label>
<input type="text" name="idCode" id="idCode"></p>
<p> <input type="submit" value="Post Notice"></p>
</form>'
?>
</div>
<script src="http://code.jquery.com/jquery-1.9.1.js"></script>
<script>
$(function () {
$('form').on('submit', function (e) {
$.ajax({
type: 'post',
url: 'postnotice.php',
data: $('form').serialize(),
success: function (data) {
if(data == 'success'){
echo "success message";
//hide the div
$('#form_div').hide(); //or $('#form').hide();
}
}
});
e.preventDefault();
});
});
</script>
postnotice.php
$idCode = $_POST['idCode'];
// then do whatever you want to do, for example if you want to insert it into db
if(saveSuccessfulIntoDb){
echo 'success';
}
try using AJAX. this will allow you to wait for a response from the server and you can choose what you want to do based on the reponse you got.
http://www.w3schools.com/ajax/default.ASP
AJAX with jQuery:
https://api.jquery.com/jQuery.ajax/

How to display a recaptcha error within the submitted form's page?

I am using the recaptcha widget on a contact form, i was wondering how would you be able to display the error the user would gets on the same page instead of going to another page and displaying the error.
You can put your form to submit on the same page, and check the post data on PHP side.
Check this example:
<?php
$captcha = $_POST['captcha'];
if(isset($captcha)) {
$captcha_answer = // you need to put your correct captcha answer here
if($captcha == $captcha_answer) {
// captcha is correct, continue.
}
else {
// captcha is not correct, display error message.
echo '<div style="background-color:red; padding:3px;">Your captcha is not correct, please try again.</div>';
echo '<form method="post">
<input type="text" name="captcha" value="Type captcha here" />
</form>'; // print the page again
}
}
else {
?>
<form method="post">
<input type="text" name="captcha" value="Type captcha here" />
</form>
<?php } ?>
Another option is to use JavaScript with AJAX.
Click here for demo
Enter "CORRECT-CAPTCHA" and click "check" button
html:
<input type="text" id="captcha"/> <!-- textbox to hold captcha text -->
<button id="check-captcha">check</button> <!-- button to check captcha -->
<div id="error-message"></div> <!-- to show error message -->
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script>
$(document).ready(function() {
$("#check-captcha").on("click", function() { // On button click
$.ajax({ // Call PHP script to check captcha
url: "checkCaptcha.php",
method: "post",
data: {
"captcha": $("#captcha").val() // Textbox holding captcha text
}
}).done(function(error) { // On PHP script finish..
$("#error-message").text(error) // Show correct/wrong message
});
});
});
</script>
php:
<?php
$captcha = $_POST['captcha']; // Get captcha text from textbox
if ($captcha == 'CORRECT-CAPTCHA') { // If text == correct captcha
echo 'correct'; // Show message
} else {
echo 'error'; // Show error
}
?>
I assume your new to AJAX, so heres an explanation on what's going on:
An "AJAX call" is just used to execute a PHP script, from JavaScript.
Button clicked
JavaScript code executed
AJAX call done to execute PHP script
PHP script executed, and returns message to JavaScript
Show message in div element

how to have a pop up contact form on submit display a confirmation message in the popup?

I'm having great issues making this contact form that can be seen on the below visual. What I want the contact form to do is display on submit a thank you message or a message of confirmation instead of redirecting to the contact.php file where there isn't any styles you can see this in action on the provided link.
I've found some information that I can do this with Jquery Ajax that I've also tried displayed below, but I still can't seem to get it to work on submit to show a message in the pop up.
Does anyone know an easier way to do this or maybe point me in the right direction as this is something that I've been trying to fix for god knows how long.
Thank you for any help
Visual:
http://madaxedesign.co.uk/dev/index.html
PHP & HTML:
<?php
$your_email = "maxlynn#madaxedesign.co.uk";
$subject = "Email From Madaxe";
$empty_fields_message = "<p>Please go back and complete all the fields in the form.</p>";
$thankyou_message = "<p>Thank you. Your message has been sent. We Will reply as soon as possible.</p>";
$name = stripslashes($_POST['txtName']);
$email = stripslashes($_POST['txtEmail']);
$message = stripslashes($_POST['txtMessage']);
if (!isset($_POST['txtName'])) {
?>
<form id="submit_message" class="hide_900" method="post" action="/contact.php" onsubmit="javascript: doSubmit();">
<div id="NameEmail">
<div>
<label for="txtName">Name*</label>
<input type="text" title="Enter your name" name="txtName" />
</div>
<div>
<label for="txtEmail">Email*</label>
<input type="text" title="Enter your email address" name="txtEmail" />
</div>
</div>
<div id="MessageSubmit">
<div>
<textarea maxlength="1200" title="Enter your message" name="txtMessage"></textarea>
<label for="txtMessage">Message</label>
</div>
<div class="submit">
<input type="submit" value="Submit" /></label>
</div>
</div>
</form>
Jquery:
function doSubmit(){
var postData = jQuery('#submit_message').serialize();
jQuery.ajax({
url: '/contact.php',
data: postData
}).done(function( html ) {
alert(html);
});
You can add return false; at the end of your doSubmit function or the following code to prevent the form to redirect the user to the action page.
var doSubmit = function (event) {
var postData = jQuery('#submit_message').serialize();
jQuery.ajax({
url: '/contact.php',
data: postData
}).done(function( html ) {
alert(html);
});
event.preventDefault();
}
$(function () {
$('#submit_message').submit(doSubmit);
});
Modified HTLM
<form id="submit_message">
...
</form>
What is this code doing ?
First, we are defining a function to submit the form data.
Notice the event argument in the function. The first variable in this function is all the form values serialized in a ajax-complient request string. The .ajax() function is sending all the datas to your server. Note that as you did not set the type argument in the .ajax() function, the data are going to be send using the GET HTTP method.
Finally, event.preventDefault() prevents the submit event to be triggered in the browser. When the browser detect a submit event, it will try to submit the form based on the action and the method parameters in the <form> html tag. Usually, this submission performs an user redirection to the action page. This event.preventDefault() will disable this redirection. Note that the event argument is going to be set automatically by jQuery.
Last part, the $(function() { ... }); part means "execute this part when the document is fully loaded." It ensures that the element with sumbit_message id exists before calling the .submit() method. This last method is an event binder. It means that when the submit event is fired on the submit_message form, the function doSubmit will be called.
I hope you have a better understanding of this script. This is a pretty basic one, but if you understand clearly the mechanics, it will help you do become a better jQuery programmer. :)
Fiddle Demo
1.<form onsubmit='confirm()'>
function confirm()
{
alert("Thank You");
}
2.in contact.php call the page that is displayed again
You need to prevent the default event of the form. To do this, add the e.preventDefault(); function to the top of your function in order to prevent this event from firing.
Also notice that we are passing the e parameter to your function. This represents the event that has been fired.
function doSubmit(e){
e.preventDefault();
var postData = jQuery('#submit_message').serialize();
jQuery.ajax({
url: '/contact.php',
data: postData
}).done(function( html ) {
alert(html);
});
}
Try this
change your form with
<form id="submit_message" class="hide_900" method="post">
and in script put it
$("#submit_message").submit(function(e){
e.preventDefault();
//call your ajax
});

Categories