Just starting playing with recaptcha and need to send form data to another file for further processing (sending to CRM). Before the captcha was implemented the form had the property action='post-sign-up', which was sending the data without problem to the post-sign-up.php.
But now with recaptcha I understand the form action property needs to be empty, and I can't figure out a way of sending the data to the other file after verifying that captcha.
When completing the form (pressing submit) the captcha is triggered. If verification fails it would show the error, but if it succeeds I need the form data to be submitted and sent to another file which does some further processing.
In other words:
user completes the form
user press submit
captcha verification occurs
if captcha is not ok, error will be shown (redirect to the same page)
if captcha is ok, the form data should be submitted to another file for further processing
(post-sign-up.php)
if post-sign-up is ok, it will show the thank you page (post-sign-up-success.php)
Thank you!
This is only client-side (no server)
sign-up.php
<script src="https://www.google.com/recaptcha/api.js?render=6Lc3UZkeAAAAAMt6wcA-bYjLenFZPGv3K5AqfvuQ"></script>
<script type="text/javascript" src="/js/libs/jquery-1.11.3.min.js"></script>
<script type="text/javascript" src="/js/libs/jquery.cookie.js"></script>
<script type="text/javascript" src="/js/libs/jquery.deparam.js"></script>
<script type="text/javascript" src="/js/libs/jquery.urlparam.js"></script>
<script type="text/javascript" src="/js/libs/jquery.fancybox.js?v=2.1.5"></script>
<script type="text/javascript" src="/js/libs/jquery.fancybox-media.js?v=1.0.6"></script>
<?php
define("RECAPTCHA_V3_SECRET_KEY", "6Lc3UZkeAAAAAIG8bVZDpkheOxM56AiMnIKYRd6z");
if(isset($_POST['token']))
{
if (isset($_POST['email']) && $_POST['email']) {
$email = filter_var($_POST['email'], FILTER_SANITIZE_STRING);
$firstName = filter_var($_POST['firstName'], FILTER_SANITIZE_STRING);
} else {
// set error message and redirect back to form...
header('location: sign-up.php');
exit;
}
$token = $_POST['token'];
$action = $_POST['action'];
// call curl to POST captcha request
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL,"https://www.google.com/recaptcha/api/siteverify");
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query(array('secret' => RECAPTCHA_V3_SECRET_KEY, 'response' => $token)));
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$response = curl_exec($ch);
curl_close($ch);
$arrResponse = json_decode($response, true);
// verify the response
if($arrResponse["success"] == '1' && $arrResponse["action"] == $action && $arrResponse["score"] >= 0.7) {
// valid submission
$captchaError = false;
// Maybe here I can send all the form data to another file which does some further processing
} else {
// spam submission
$captchaError = true;
}
}
?>
<section class="lc-layout-component border bank-font">
<div class="lc-content component-padding gutters">
<section class="cc-column-component regular-grid">
<?php if (isset($this) && $this->wasError()) { ?>
<div class="error">
<p><?php echo $this->getErrorMessage(); ?></p>
</div>
<?php
}?>
<!--old action: /post-sign-up -->
<form id="bank-form" class="form clear one-full cf-contact-form" action="?" method="POST" data-tracking="contact_sales">
<div>
<label class="label mandatory bank-color bank-label" for="firstName">First Name</label>
<input id="firstName" value="Pepe" type="text" class="one-full bank-color-grey bank-input" name="firstName" placeholder="First Name" autocomplete="off" data-validate="true" data-type="text" data-min="3" value="<?php isset($this) ? print $this->getFirstName() : print ''; ?>">
<br/>
<label class="label mandatory bank-color bank-label" for="lastName">Last Name</label>
<input id="lastName" value="Chanches" type="text" class="one-full bank-color-grey bank-input" name="lastName" placeholder="Last Name" autocomplete="off" data-validate="true" data-type="text" data-min="3" value="<?php isset($this) ? print $this->getLastName() : print ''; ?>">
<br/>
<label class="label mandatory bank-color bank-label" for="company">Company</label>
<input id="company" value="Pepe Ltd" type="text" class="one-full bank-color-grey bank-input" name="company" placeholder="Company" autocomplete="off" data-validate="true" data-type="text" data-min="3" value="<?php isset($this) ? print $this->getCompany() : print ''; ?>">
<br/>
<label class="label mandatory bank-color bank-label" for="email">Email</label>
<input value="asdf#asdf.com" id="email" type="text" class="one-full bank-color-grey bank-input" name="email" placeholder="Email" autocomplete="off" data-validate="true" data-type="email" value="<?php isset($this) ? print $this->getEmail() : print ''; ?>">
<br/>
<label class="label mandatory bank-color bank-label" for="phone">Phone</label>
<input id="phone" value="+4565464565" type="text" class="one-full bank-color-grey bank-input" name="phone" placeholder="Phone" autocomplete="off" data-validate="true" data-type="phone" value="<?php isset($this) ? print $this->getPhone() : print ''; ?>">
<br/>
<label class="label bank-color bank-label" for="referredBy">Referred by </label>
<input id="referredBy" value="Pepa" type="text" class="one-full bank-color-grey bank-input" name="referredBy" placeholder="Referred By" autocomplete="off" value="<?php isset($this) ? print $this->getCashManager() : print ''; ?>">
</div>
<div class="row inline one-full">
<br/>
<!-- <div class="g-recatpcha" data-sitekey="6Lc3UZkeAAAAAMt6wcA-bYjLenFZPGv3K5AqfvuQ"></div> -->
<button type="submit"
value="submit"
>
<a>Submit form</a>
</button>
<div class="field inline one-full">
<br/>
<?php
isset($arrResponse["score"]) && $captchaError == true && print 'error. Please try again later ';
print ' score: ';
print $arrResponse["score"];
?>
</div>
<input type="hidden" name="recaptcha_response" id="recaptchaResponse">
</div>
</form>
</section>
</div>
</section>
<script>
$('#bank-form').submit(function(event) {
console.log('subtmitting');
event.preventDefault();
var email = $('#email').val();
console.log(email);
var firstName = $("#firstName").val();
console.log(firstName);
grecaptcha.ready(function() {
grecaptcha.execute('6Lc3UZkeAAAAAMt6wcA-bYjLenFZPGv3K5AqfvuQ', {action: 'submit'}).then(function(token) {
$('#bank-form').prepend('<input type="hidden" name="token" value="' + token + '">');
$('#bank-form').prepend('<input type="hidden" name="action" value="submit">');
$('#bank-form').unbind('submit').submit();
});;
});
});
</script>
Related
On Checkbox Changed event I am copying hidden values to my textbox,
now when I try to add value using jquery its gives me [Object object].
HTML Code
My hidden variables values
<div class="reserve-form">
<span>Name: </span><span><?php echo $user_data[0]->first_name.' '.$user_data[0]->last_name; ?>
<input type="hidden" id="name_account" value="<?php echo $user_data[0]->first_name.' '.$user_data[0]->last_name; ?>" />
</span>
<span>Email Address: </span><span><?php echo $user_data[0]->email_id; ?>
<input type="hidden" id="email_account" value="<?php echo $user_data[0]->email_id; ?>" />
</span>
<span>Phone Number: </span><span><?php echo $user_data[0]->phone_no; ?>
<input type="hidden" id="phoneno_account" value="<?php echo $user_data[0]->phone_no; ?>">
</span>
<div class="passenger-checkbox">
<input type="checkbox" name="duplicate_info" id="duplicate_info" class="css-checkbox" />
<label for="duplicate_info" class="css-label">Is passenger info same as account holder</label>
</div>
</div>
**Where I need to append it**
<div id="passanger_info">
<input type="text" class="form-control" id="name[]" name="name[]" placeholder="Name">
<input type="text" class="form-control" id="email_address[]" name="email_address[]" placeholder="Email Address">
<input type="text" class="form-control" id="phone_number[]" name="phone_number[]" placeholder="Phone Number">
<button type="button" class="removebtn"><i class="fa fa-times"></i></button>
</div>
$("#duplicate_info").change(function() {
if(this.checked)
{
isChecked();
}
else
{
alert("Unchecked")
}
});
function isChecked()
{
//hidden variables values
var name_account = $('#name_account').val();
var email_account = $('#email_account').val();
var phoneno_account = $('#phoneno_account').val();
alert(name_account);
var name = $('#name').val(name_account);
alert(name);
var email_address = $('#email_address').val(email_account);
var phone_number = $('#phone_number').val(phoneno_account);
}
It's like when I copy name_account to name and try to alert the name it gives me Object Object instead of values. What I am missing?
You have to set the value, before you take from it.
setting value = $('#name').val(name_account)
taking the value = var name = $('#name').val();
The problem in your code is [] in your id
$("#duplicate_info").change(function() {
if (this.checked) {
isChecked();
} else {
alert("Unchecked")
}
});
function isChecked() {
//hidden variables values
var name_account = $('#name_account').val();
console.log("input val of #name_account is : " + name_account);
$('#name').val(name_account)
var name = $('#name').val();
console.log("input val of #name is : " + name);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="reserve-form">
<span>Name: </span><span>Carsten
<input type="hidden" id="name_account" value="Carsten" />
</span>
<span>Email Address: </span><span><?php echo $user_data[0]->email_id; ?>
<input type="hidden" id="email_account" value="<?php echo $user_data[0]->email_id; ?>" />
</span>
<span>Phone Number: </span><span><?php echo $user_data[0]->phone_no; ?>
<input type="hidden" id="phoneno_account" value="<?php echo $user_data[0]->phone_no; ?>">
</span>
<div class="passenger-checkbox">
<input type="checkbox" name="duplicate_info" id="duplicate_info" class="css-checkbox" />
<label for="duplicate_info" class="css-label">Is passenger info same as account holder</label>
</div>
</div>
**Where I need to append it**
<div id="passanger_info">
<input type="text" class="form-control" id="name" name="name[]" placeholder="Name">
<input type="text" class="form-control" id="email_address[]" name="email_address[]" placeholder="Email Address">
<input type="text" class="form-control" id="phone_number[]" name="phone_number[]" placeholder="Phone Number">
<button type="button" class="removebtn"><i class="fa fa-times"></i></button>
</div>
Check below example:
Fill up the details and click on checkbox.
$("#duplicate_info").change(function() {
if(this.checked)
{
isChecked();
}
else
{
alert("Unchecked")
}
});
function isChecked()
{
//hidden variables values
var name_account = $('#name_account').val();
var email_account = $('#email_account').val();
var phoneno_account = $('#phoneno_account').val();
alert(name_account);
$('#name').val(name_account);
var name = $('#name').val();
alert(name);
var email_address = $('#email_address').val(email_account);
var phone_number = $('#phone_number').val(phoneno_account);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
My hidden variables values
<div class="reserve-form">
<span>Name: </span><span>
<input type="hidden" id="name" value="" />
</span>
<span>Email Address: </span><span>
<input type="hidden" id="email_account" value="" />
</span>
<span>Phone Number: </span><span>
<input type="hidden" id="phoneno_account" value="">
</span>
<div class="passenger-checkbox">
<input type="checkbox" name="duplicate_info" id="duplicate_info" class="css-checkbox" />
<label for="duplicate_info" class="css-label">Is passenger info same as account holder</label>
</div>
</div>
**Where I need to append it**
<div id="passanger_info">
<input type="text" class="form-control" id="name_account" name="name_account[]" placeholder="Name">
<input type="text" class="form-control" id="email_address" name="email_address[]" placeholder="Email Address">
<input type="text" class="form-control" id="phone_number" name="phone_number[]" placeholder="Phone Number">
<button type="button" class="removebtn"><i class="fa fa-times"></i></button>
</div>
I am using the code below, but want error messages when the user skips a required field. Can anyone help, please? So if a user forgets to fill the required input filed "first name", that an error message appears above the field with the text "First name is a required field".
<form id="comment_form" action="form.php" method="post">
<div class="compulsoryfield">
<input class="inputfield-radio" type="radio" name="gender" value="Mr" required><label class="label-radio">Mr.</label>
<input class="inputfield-radio" type="radio" name="gender" value="Ms"><label class="label-radio">Ms.</label>
<span class="requiredmark-radio">*</span>
</div>
<div class="compulsoryfield"><span class="requiredmark">*</span>
<input class="inputfield3" type="firstname" placeholder="first name" required>
</div>
<div class="compulsoryfield"><span class="requiredmark">*</span>
<input class="inputfield1" type="lastname" placeholder="last name" required>
</div>
<input class="inputfield2" type="companyname" placeholder="company name (if applicable)">
<input class="inputfield2" type="customernumber" placeholder="customer number (on invoice if available)" >
<br><br>
<div class="compulsoryfield"><span class="requiredmark">*</span>
<input class="inputfield3" type="email" placeholder="email address" required>
</div>
<div class="compulsoryfield"><span class="requiredmark">*</span>
<input class="inputfield1" type="emailagain" placeholder="re-enter email address (to confirm)" required>
</div>
<input class="inputfield2" type="telephonenumber" placeholder="telephone number (country code included)">
<br><br>
<div class="compulsoryfield"><span class="requiredmark">*</span>
<input class="inputfield3" type="subject" placeholder="subject of message" required>
</div>
<div class="compulsoryfield"><span class="requiredmark">*</span>
<textarea id="textareafieldid" class="textareafield" name="message" placeholder="add your message here" rows="8" cols="39" required></textarea></div><br><br>
<p id="recaptcha-header">before sending, please show us you're real:</p>
<div><span class="requiredmark">*</span><div id="g-recaptcha-outer" class="compulsoryfield2">
<div class="g-recaptcha" data-sitekey="mySitekey"></div></div><br><br>
<input id="button-type1" type="submit" name="submit" value="SEND">
</form>
and
<?php
$email;$comment;$captcha;
if(isset($_POST['gender'])){
$email=$_POST['gender'];
}if(isset($_POST['firstname'])){
$email=$_POST['firstname'];
}if(isset($_POST['lastname'])){
$email=$_POST['lastname'];
}if(isset($_POST['companyname'])){
$email=$_POST['companyname'];
}if(isset($_POST['customernumber'])){
$email=$_POST['customernumber'];
}if(isset($_POST['email'])){
$email=$_POST['email'];
}if(isset($_POST['emailagain'])){
$email=$_POST['emailagain'];
}if(isset($_POST['telephonenumber'])){
$email=$_POST['telephonenumber'];
}if(isset($_POST['subject'])){
$email=$_POST['subject'];
}if(isset($_POST['message'])){
$email=$_POST['message'];
}if(isset($_POST['g-recaptcha-response'])){
$captcha=$_POST['g-recaptcha-response'];
}
if(!$captcha){
echo '<h2>Please check the captcha form.</h2>';
exit;
}
$secretKey = "mtSecretKey";
$ip = $_SERVER['REMOTE_ADDR'];
$response=file_get_contents("https://www.google.com/recaptcha/api/siteverify?secret=".$secretKey."&response=".$captcha."&remoteip=".$ip);
$responseKeys = json_decode($response,true);
if(intval($responseKeys["success"]) !== 1) {
echo '<h2>You are a spammer !</h2>';
} else {
echo '<h2>Thanks for your email.</h2>';
}
?>
I suggest you to try js plugins like :
http://parsleyjs.org/
or
http://www.formvalidator.net/
You gonna see, the first is for me the best , and the second is very simple.
With the second you just have to add an attribute rules to your field like :
data-validation="required".
With this example you can required a field.
send the destination of the form to the same page the form is on.
At the top of the page before any html code is sent to the client, do your form handling.
$problemstring = "";
$firstname = "";
if(isset($_POST['submit'])){
if(!isset($_POST['firstname'])){$problemstring = "Error in firstname"}
//repeat for all fields
}
if(strlen($problemString)==0) {
//Do database actions here
//The Line below redirects to another page if form good
if(strlen($problemString)==0) die(header('Location: index.php'));
}
This code you check your form for blank data then if there are no problems run the database operations. If there is a problem the rest of the page will load.
Put the code below where you want the error message to be displayed.
<?php
if(strlen($problemString)>0) {
echo '<table><tr>';
echo '<td colspan="3">';
echo '<font color="#FF0000"><strong>There was a problem with your form</strong><br>';
echo $problemString;
echo '</font></td>';
echo '</tr>';
echo '<tr><td colspan="3" height="16"></td></tr></table>';
}
?>
In your form do this:
<input class="inputfield3" type="firstname" placeholder="first name" value="<?php echo $firstname; ?>" required>
this will populate the field with what was entered into the form before the submit, if this was the empty field it would be blank. if the page is loaded for the first time the value would be blank (or whatever you set).
Ive used this in my website and it works well.
Hi I've got a problem with submitting my own simple form in Wordpress it always redirects me to the page witch not exists. I use almost all thing for action field in form like (get_permalink,$_SERVER["PHP_SELF"]) and even did it manually.
<?php
if (isset($_POST["email"]) && $_POST["email"]) {
$content = "user email: {$_POST["email"]}; phone : {$_POST['phone']} ";
$subject = "Test email ";
$to = "some#gmail.com";
$status = wp_mail($to,$subject,$content);
}
?>
<div class="center form-wrapper">
<form action="<?php echo get_permalink(); ?>" method="post">
<h2 class="center white form-logo">
Subscribe
</h2>
<input type="text" placeholder="Enter email" name="email">
<input type="text" placeholder="Enter name" name="name">
<input type="text" placeholder="Enter phone number" name="phone">
<input type="hidden">
<input type="submit" name="submit" value="send" >
</form>
I am currently learning forms and Ajax posting without a page refresh. I have tree forms and one submit button. I have assigned php variables to each input field that will take the value of what’s typed in. The value is echoed for each input box. Is it possible to submit all three forms at the same time? And if yes, how would I submit these values to a MySQL database after the button click?
Ajax:
function() {
$.ajax({
type: "POST",
url: "posting.php",
data: {
"name": $("#name").val(),
"age": $("#age").val(),
"phone": $("#phone").val(),
"email": $("#email").val(),
"job": $("#job").val(),
"hobby": $("#hobby").val(),
},
success: function(data) {
$("#inputResult").html(data);
}
});
}
PHP
if ($_SERVER['REQUEST_METHOD'] == 'POST')
{
if (isset($_POST['name'])) {
$name = $_POST['name'];
echo '<div id="name_input"><h2 class="lastTab">Name:</h2>' . $name . '</div>';
}
if (isset($_POST['age'])) {
$age = $_POST['age'];
echo '<div id="age_input"><h2 class="lastTab">Age:</h2>' . $age . '</div>';
}
if (isset($_POST['phone'])) {
$phone = $_POST['phone'];
echo '<div id="phone_input"><h2 class="lastTab">Phone:</h2>' . $phone . '</div>';
}
if (isset($_POST['email'])) {
$email = $_POST['email'];
echo '<div id="email_input"><h2 class="lastTab">Email:</h2>' . $email . '</div>';
}
if (isset($_POST['job'])) {
$job = $_POST['job'];
echo '<div id="job_input"><h2 class="lastTab">Job:</h2>' . $job . '</div>';
}
if (isset($_POST['hobby'])) {
$hobby = $_POST['hobby'];
echo '<div id="hobby_input"><h2 class="lastTab">Hobby:</h2>' . $hobby . '</div>';
}
}
HTML
<div id="tab-1" class="ui-tabs-panel ui-tabs-hide">
<form autocomplete="off" method="post" enctype="multipart/form-data" id="postForm1" name="postForm1" class="postForm">
Name
<input type="text" id="name" class="detail" name="name" value="" />
Age
<input type="text" id="age" class="detail" name="age" value="" />
</form>
</div>.
<div id="tab-2" class="ui-tabs-panel ui-tabs-hide">
<form autocomplete="off" method="post" enctype="multipart/form-data" id="postForm2" name="postForm2" class="postForm">
Phone Number
<input type="text" id="phone" class="detail" name="phone" value="" />
Email
<input type="text" id="email" class="detail" name="email" value="" />
</form>
</div>
<div id="tab-3" class="ui-tabs-panel ui-tabs-hide">
<form autocomplete="off" method="post" enctype="multipart/form-data" id="postForm3" name="postForm3" class="postForm">
Job
<input type="text" id="job" class="detail" name="job" value="" />
Hobby
<input type="text" id="hobby" class="detail" name="hobby" value="" />
</form>
</div>
You can either use javascript to catch the submit of the form or you can trigger a function that you ve created. It doesn t have to be 3 forms or even a form element for the second case to work
HTML:
<div id="tab-1" class="ui-tabs-panel ui-tabs-hide">
<form autocomplete="off" method="post" enctype="multipart/form-data" id="postForm1" name="postForm1" class="postForm">
Name
<input type="text" id="name" class="detail" name="name" value="" />
Age
<input type="text" id="age" class="detail" name="age" value="" />
</form>
</div>.
<div id="tab-2" class="ui-tabs-panel ui-tabs-hide">
<form autocomplete="off" method="post" enctype="multipart/form-data" id="postForm2" name="postForm2" class="postForm">
Phone Number
<input type="text" id="phone" class="detail" name="phone" value="" />
Email
<input type="text" id="email" class="detail" name="email" value="" />
</form>
</div>
<div id="tab-3" class="ui-tabs-panel ui-tabs-hide">
<form autocomplete="off" method="post" enctype="multipart/form-data" id="postForm3" name="postForm3" class="postForm">
Job
<input type="text" id="job" class="detail" name="job" value="" />
Hobby
<input type="text" id="hobby" class="detail" name="hobby" value="" />
<input type="button" value="SAVE" onclick="saveThem()" />
</form>
</div>
AJAX:
function saveThem() {
var name = $.trim($("#name").val());
var age = $.trim($("#age").val());
var phone = $.trim($("#phone").val());
var email = $.trim($("#email").val());
var job = $.trim($("#job").val());
var hobby = $.trim($("#hobby").val());
var dataString = 'name='+name+'&age='+age+'&phone='+phone+'&email='+email+'&job='+job+'&hobby='+hobby;
$.ajax({
type: "POST",
url: 'http://www.yourdomain.com/something.php',
data: dataString,
dataType: "json",
success: function(data) {
if(data.response){ alert(data.message); }
$("#inputResult").html(data);
}
});
}
something.php
//Get posted variables
$name = (isset($_POST['name'])) ? strip_tags($_POST['name']) : NULL;
$age = (isset($_POST['age'])) ? strip_tags($_POST['age']) : NULL;
$phone = (isset($_POST['phone'])) ? strip_tags($_POST['phone']) : NULL;
$email = (isset($_POST['email'])) ? strip_tags($_POST['email']) : NULL;
$job = (isset($_POST['job'])) ? strip_tags($_POST['job']) : NULL;
$hobby = (isset($_POST['hobby'])) ? strip_tags($_POST['hobby']) : NULL;
//execute your query
$sql = "INSERT INTO ...";
//Return results back to ajax
$result = array(
'response' => 1,
'message' => 'We have a success!'
);
echo json_encode($result);
So in conclusion is pretty much the same as using php but in the middle there is some javascript.
Form: create an id for each element that you want to send to your server(php)
Js: catch values based on element ids and send them to php
Php: get values, clean them, query or anything else and send results back to js
EDIT: Using jQuery serialize()
$('form').submit(function() {
$dataString = $(this).serialize(); //This will produce the same result, based on input names
});
I am trying to create error messages if certain conditions aren't met. So the user fills out a form and if a field is empty or doesn't pass my validation it returns the error message.
This is the form:
if (isset($_POST)) {
if (checkEmail($email) == TRUE && $name != NULL && $surName != NULL) {
mysql_query( "INSERT INTO USR_INFO (NAME, MAIL, SURNAME)
VALUES ('$name', '$email','$surName') ") or die(mysql_error());
header('Location: thanks.php');
}
else {
echo'<form action="<?php echo $_SERVER[\'PHP_SELF\']; ?>" method="POST">
<label for="name">First Name</label>
<input type="text" name="name" id="name" value="' .$_POST['name'].'" />
<span class="required">*</span>
<label for="surName">Last Name</label>
<input type="text" name="surName" id="surName" value="' .$_POST['surName']. '" />
<span class="required">*</span>
<label for="email">E-mail</label>
<input type="email" id="email" name="email" placeholder="example#domain.com" value="' .$_POST['email']. '" />
<span class="required">*</span>
<input type="submit" name="submit" id="submit">
</form>';
}
} else {
echo'<form action="<?php echo $_SERVER[\'PHP_SELF\']; ?>" method="POST">
<label for="name">First Name</label>
<input type="text" name="name" id="name" value="" />
<span class="required">*</span>
<label for="surName">Last Name</label>
<input type="text" name="surName" id="surName" value="" />
<span class="required">*</span>
<label for="email">E-mail</label>
<input type="email" id="email" name="email" placeholder="example#domain.com" value="" />
<span class="required">*</span>
<input type="submit" name="submit" id="submit">
</form>';
}
So what I tried is adding an array to display the error messages like so:
$errorMessage = array();
And add this to the html form field with the proper message:
$error[] = "Error Message";
Now what I am stuck with is that I want to have the error show only if a user doesn't meet the conditions
if ($name == NULL) {$error[] = "Error Message";}
if ($surName == NULL) {$error[] = "Error Message 2";}
if (checkEmail($email) == FALSE || NULL) {$error[] = "Error Message 3";}
But I can't make it work. When I tried to implement this logic it will parse the page fine and the validation works as well but the error messages wont show up if I leave a required field blank. My guess is that I didn't loop through it properly.
Help is much appreciated!
EDIT:
I tried the answer that was posted by Frosty Z and this is what I have at the moment:
if (isset($_POST)) {
$errorMessage = array();
if ($name == '') { $errors[] = "Input name please." }
if ($surName == '') { $errors[] = "Input last name please." }
if (!checkEmail($email)) { $errors[] = "Email address not valid." }
if (count($error) == 0) {
mysql_query( "INSERT INTO USR_INFO (NAME, MAIL, SURNAME)
VALUES ('$name', '$email', '$surName') ") or die(mysql_error());
header('Location: thanks.php');
exit;
else {
if (count($errors) > 0)
echo "<p>Sorry, there are problems with the information you have provided:</p>";
foreach($errors as $error)
echo '<p class="error">'.$error.'</p>';
echo'<form action="<?php echo $_SERVER[\'PHP_SELF\']; ?>" method="POST">
<label for="name">Name</label>
<input type="text" name="name" id="name" value="' .$_POST['name'].'" />
<span class="required">*</span>
<label for="surName">Last name</label>
<input type="text" name="surName" id="surName" value="' .$_POST['surName']. '" />
<span class="required">*</span>
<label for="email">E-mail</label>
<input type="email" id="email" name="email" placeholder="example#domain.com" value="' .$_POST['email']. '" />
<span class="required">*</span>
<input type="submit" name="submit" id="submit">
</form>';
}
} else {
echo'<form action="<?php echo $_SERVER[\'PHP_SELF\']; ?>" method="POST">
<label for="name">Name</label>
<input type="text" name="name" id="name" value="" />
<span class="required">*</span>
<label for="surName">Achternaam</label>
<input type="text" name="surName" id="surName" value="" />
<span class="required">*</span>
<label for="email">E-mail</label>
<input type="email" id="email" name="email" placeholder="example#domain.com" value="" />
<span class="required">*</span>
<input type="submit" name="submit" id="submit">
</form>';
}
With this my page won't be parsed. I have error reporting on but it doesn't show anything besides a
Internal server error 500
in my console log(Firebug)
Here is some rewriting of your work with a minimal handling of error messages.
BTW, you should consider adopting a decent PHP framework which will help you to handle a lot of common development tasks.
$name = '';
$surName = '';
$email = '';
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
$name = $_POST['name'];
$surName = $_POST['surName'];
$email = $_POST['email'];
$errors = array();
if ($name == '') { $errors[] = "Please type your name."; }
if ($surName == '') { $errors[] = "Please type your surname."; }
if (!checkEmail($email)) { $errors[] = "Wrong email format."; }
if (count($errors) == 0) {
// tip: use PDO or mysqli functions instead of mysql ones to bind variables.
// currently there is a risk of SQL injection here
mysql_query("INSERT INTO USR_INFO (NAME, MAIL, SURNAME)
VALUES ('$name', '$email','$surName') ") or die(mysql_error());
header('Location: thanks.php');
exit;
}
}
if (count($errors) > 0)
echo '<p>Sorry, there are problems with the information you have provided:</p>';
foreach($errors as $error)
echo '<p class="error">'.$error.'</p>';
echo '<form action="'.$_SERVER['PHP_SELF'].'" method="POST">
<label for="name">First Name</label>
<input type="text" name="name" id="name" value="'.htmlspecialchars($name).'" />
<span class="required">*</span>
<label for="surName">Last Name</label>
<input type="text" name="surName" id="surName" value="'.htmlspecialchars($surName).'" />
<span class="required">*</span>
<label for="email">E-mail</label>
<input type="email" id="email" name="email" placeholder="example#domain.com" value="'.htmlspecialchars($email).'" />
<span class="required">*</span>
<input type="submit" name="submit" id="submit">
</form>';