Validate php form fail - php

This code works fine in seperated file named form.php, but when i paste it to
wordpress theme page it does not even validate form and not even send mail of course. Why is there no any action after i clikced submit button in wordpress theme?
Anyone can help me to solve problem?
get_header();
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
$nameError = $mailError = $messageError = '';
function validate($data){
if(empty($data)){
return false;
}else{
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
}
//Validate name input
if(!validate($_POST['name'])){
$nameError = 'Polje ime je obavezno.';
}else{
if (!preg_match("/^[a-zA-Z ]*$/",$_POST['name'])) {
$nameError = "Polje moze sadrzavati samo slova i razmak";
}
}
//Validate email input
if(!validate($_POST['email'])){
$mailError = 'Polje email je obavezno';
}else{
if (!filter_var($_POST['email'], FILTER_VALIDATE_EMAIL)) {
$mailError = "Nevazeća email adresa";
}
}
//Validate message textarea
if(!validate($_POST['message'])){
$messageError = 'Molimo unesite poruku';
}
if(empty($nameError) && empty($mailError) && empty($messageError)){
//Create the body
$body = "Ime: {$_POST['name']}\n\nPoruka: {$_POST['message']}";
//Make it no longer than 70 characters long
$body = wordwrap($body, 70);
//Send the mail
mail('example#example.com', 'Contact Form Submission',
$body,
"From: {$_POST['email']}");
//Print a message
echo '<p><em>Thank you for contacting me. I will reply some day.
</em></p>';
}else{
echo '<p style="font-weight: bold; color: #C00">Please fill out
the
form completley.</p>';
}
}
HTML Code that is placed in same file as php validation
<section class="contact-img">
<div class="container-fluid">
<div class="row">
<?php the_post_thumbnail(); ?>
</div>
</div>
</section>
<section class="contact">
<div class="container">
<div class="row">
<?php dynamic_sidebar('contact-page'); ?>
<div class="col-md-12">
<h4 class="col-xs-12 text-center"><strong>Ostavite
poruku</strong></h4>
</div>
</div>
</div>
<div class="container">
<div class="row">
<div class="col-xs-10 col-xs-offset-1 col-sm-6 col-sm-offset-3">
<form method="POST" action="<?php echo
htmlspecialchars($_SERVER["PHP_SELF"]);?>">
<div class="form-group">
<input type="text" class="form-control" name="name"
value="" placeholder="Ime">
<div><?php if(isset($nameError)) echo $nameError; ?>
</div>
</div>
<div class="form-group">
<input type="text" class="form-control" name="email"
value="" placeholder="E-mail">
<div><span class="error"><?php if(isset($mailError))
echo $mailError; ?></span></div>
</div>
<div class="form-group">
<textarea class="form-control" name="message" rows="3"
placeholder="Poruka"></textarea>
<div><span class="error"><?php
if(isset($messageError)) echo $messageError; ?></span></div>
</div>
<input class="btn btn-default" type="button" name="button"
value="Pošalji">
</form>
</div>
</div>
</div>
</section>

You have a syntax error (white page of death, if error reporting is off)
$nameError = 'Polje moze sadrzavati samo slova i razmak;
Should be:
$nameError = 'Polje moze sadrzavati samo slova i razmak';
Another thing that might get you is your name validation Regex is to simple, it doesn't account for things like Jane Doe-Smith, or J o h n S m i t h or j or even '', an empty string.
I would use something like this:
if(!preg_match("/^([a-z]+)\s+(?:([a-z]+)\s+)?([-a-z]+)$/i" , $_POST['name'])){
$nameError = 'Polje moze sadrzavati samo slova i razmak;
}
Regex:
([a-z]+) matches a though z (first 2 capture groups)
\s+ matches one or more space
(?...) non-capture group ? optionally, middle name
([-a-z]+) matches - and a though z (for hyphenated last names)
\i case insensitive flag.
Regex Test
Test cases:
John Smith {match}
John E Smith {match}
Jane J Doe-Smith {match}
John {no match}
Which is still a small sample size, but should cover most English names ( not sure what language this is Polje moze).
I once dated a girl many many years ago with a hyphenated last name ... lol.
The last thing is to turn on display errors and set error reporting to a value like E_ALL (for development). I'd say use ini_set('display_errors', '1') and error_reporting() but they won't catch syntax errors in the same file (generally).

Related

How to display message in HTML Tag with PHP in a function

I have this PHP form validator that is also hooked up to a mail function and to keep things organized I did the form validation in a separate function that is being called when the form is submitted.
Now I have this problem that I don't know how to display the error message when a field is empty in the HTML form.
Can anyone help? Thank you in advance.
I'm also pretty new to PHP and the whole thing.
PHP:
<?php
// Validation function
function validation($name, $email, $message) {
// Searching for every empty POST variable
// And if empty push into $error array
if (empty($name)) {
array_push($errors, "Name");
}
if (empty($email)) {
array_push($errors, "E-Mail");
} else if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
$mail_error = " and E-Mail must be correct/filled out.";
}
if (empty($message)) {
array_push($errors, "Message");
}
// Combining all index of array to one final string
$final = implode(", ", $errors);
// Adding additional string to final
$final .= " is not allowed to be empty." . $mail_error . "\n";
return $final;
}
if (isset($_POST["submit"])) {
// Defining POST variables for validation and mail content
$fname = $_POST["fname"];
$femail = $_POST["femail"];
$fmessage = $_POST["fmessage"];
// Defining variable for pushing errors for validation
$errors = array();
// Calling function
validation($fname, $femail, $fmessage);
}
HTML:
<form name="main-form" action="" method="post" class="row g-3 pt-1 p-5 bg-custom">
<div class="input-group mb-3 col-md-6">
<span class="input-group-text">Name</span>
<input name="fname" type="text" class="form-control me-3 " placeholder="Name" aria-label="Name">
<span class="input-group-text">E-Mail</span>
<input name="femail" type="email" class="form-control" placeholder="example#mail.com"aria-label="example#mail.com">
</div>
<div class="input-group mb-3 col-md-12 col-sm-6">
<span class="input-group-text">Message</span>
<textarea name="fmessage" type="text" class="form-control"></textarea>
</div>
<!-- The error message if a field is empty should be displayed here: -->
<p id="error-message" class="text-center text-danger"><?php echo($final); ?></p>
<div class="col-md-12 text-center">
<button class="btn btn-primary me-2" id="btn-send" style="width: 30%;" class="btn btn-primary me-2" type="submit" name="submit">Send</button>
</div>
</form>
<?php
// Validation function
function validation($name, $email, $message) {
$errors = [];
$final = "";
// Searching for every empty POST variable
// And if empty push into $error array
if (empty($name)) {
array_push($errors, "Name");
}
if (empty($email)) {
array_push($errors, "E-Mail");
} else if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
$mail_error = " and E-Mail must be correct/filled out.";
}
if (empty($message)) {
array_push($errors, "Message");
}
// Combining all index of array to one final string
$final = implode(", ", $errors);
// Adding additional string to final
$final .= " is not allowed to be empty." . $mail_error . "\n";
return $final;
}
if (isset($_POST["submit"])) {
// Defining POST variables for validation and mail content
$fname = $_POST["fname"];
$femail = $_POST["femail"];
$fmessage = $_POST["fmessage"];
// Defining variable for pushing errors for validation
// Calling function
$error = validation($fname, $femail, $fmessage);
}
HTML
<form name="main-form" action="" method="post" class="row g-3 pt-1 p-5 bg-custom">
<div class="input-group mb-3 col-md-6">
<span class="input-group-text">Name</span>
<input name="fname" type="text" class="form-control me-3 " placeholder="Name" aria-label="Name">
<span class="input-group-text">E-Mail</span>
<input name="femail" type="email" class="form-control" placeholder="example#mail.com"aria-label="example#mail.com">
</div>
<div class="input-group mb-3 col-md-12 col-sm-6">
<span class="input-group-text">Message</span>
<textarea name="fmessage" type="text" class="form-control"></textarea>
</div>
<!-- The error message if a field is empty should be displayed here: -->
<p id="error-message" class="text-center text-danger"><?=if(isset($error)); $error : "";?></p>
<div class="col-md-12 text-center">
<button class="btn btn-primary me-2" id="btn-send" style="width: 30%;" class="btn btn-primary me-2" type="submit" name="submit">Send</button>
</div>
</form>
$error = validation($fname, $femail, $fmessage); store data in variable and
isset() use to check variable exist or not

Form validation in php - the error and success message display at the same time

I'm learning coding and created a simple form where error messages are
displayed just below each input field. However, when I check the form
the success message appears at the same time as error messages instead
of displaying when all the fields are correctly entered and form
validated. Can you please help. Thank yo in advance. Here is my
code.
</php>
$errorMessage = "";
$successMessage = "";
$emailError = "";
$emailconfirmError = "";
$nameError = "";
$messageError = "";
$servicesError = "";
$name = $email = $emailConfirm = $services = $message = "";
$email = isset($_POST['email']) ? $_POST['email'] : '';
$emailConfirm = isset($_POST['emailConfirm']) ? $_POST['emailConfirm'] : '';
if ($_POST) {
if (!$_POST['email']) {
$emailError .="The email is required";
}
if (!$_POST['emailConfirm']) {
$emailconfirmError .="Please confirm your email <br>";
}
if ($_POST['emailConfirm'] && $email != $emailConfirm) {
$emailconfirmError .="The email addresses do not match <br>";
}
if (!$_POST['name']) {
$nameError .="The name field is required <br>";
}
if (!$_POST['services']) {
$servicesError .="Please select a service required <br>";
}
if (!$_POST['message']) {
$messageError .="The message field is required <br>";
}
if ($_POST['email'] && filter_var($_POST['email'], FILTER_VALIDATE_EMAIL) === false) {
$emailError .= "The email address is invalid.<br>";
}
if ($name = $email = $emailConfirm = $services = $message != "") {
echo $emailError;
echo $emailconfirmError;
echo $name;
echo $services;
echo $message;
}else {
$emailTo = "kamala_guliyeva#hotmail.com";
$services = $_POST['services'];
$message = $_POST['message'];
$headers = "From: ".$_POST['email'];
if (mail($emailTo, $services, $message, $headers)) {
$successMessage = '<div class="alert alert-success" role="alert">Thank you for your message. We\'ll get back to you ASAP!</div>';
} else {
$errorMessage = '<div class="alert alert-danger" role="alert"><p>Your message couldn\'t be sent - please try again</div>';
}
}
}
and HTML
<div id="quote">
<div class="container">
<h2 class="section-title">Request a Quote</h2>
<hr align="left" width="8%" class="style-one">
<br>
<div><? echo $errorMessage.$successMessage; ?></div>
<form id="quoteForm" method="post">
<div class="row">
<div class="col-md-6">
<div class="form-group">
<input type="email" class="form-control" style="height:60px" id="email" name="email" placeholder="Your email">
<label class="error" id="emailError"><?php echo $emailError; ?></label>
</div>
<div class="form-group">
<input type="email" class="form-control" style="height:60px" id="emailConfirm" name="emailConfirm" placeholder="Re-type your email">
<label class="error" for="e-mailConfirm" id="emailconfirmError"><?php echo $emailconfirmError; ?></label>
</div>
<div class="form-group">
<input type="name" class="form-control" id="name" style="height:60px" name="name" placeholder="Your Name">
<label class="error" for="name" id="nameError"><?php echo $nameError; ?></label>
</div>
</div>
<div class="col-md-6">
<div class="form-group">
<select class="form-control" id="services" name="services" style="height:60px">
<option value="">Select Services</option>
<option value="Installation">Installation</option>
<option value="Repair">Repair</option>
<option value="Service and Maintenance">Service and Maintenance</option>
</select>
<label class="error" for="services" id="servicesError"><?php echo $servicesError; ?></label>
</div>
<div class="form-group">
<textarea class="form-control" id="message" name="message" placeholder="Message" style="height: 163px;" cols="35"></textarea>
<label class="error" for="message" id="messageError"><?php echo $messageError; ?></label>
</div>
</div>
</div>
<div class="form-row text-center">
<div class="col-12">
<button type="submit" style="width:10rem" class="btn quoteButton pt-3 pb-3 text-align-center">Get a Quote</button>
</div>
</div>
</form>
</div>
</div>
You've a few problems there...
So first thing is how you are doing your checks.
if(!$_POST) {
is not a valid way of checking that a post has occurred you need to do something like
if(isset($_POST) && !empty($_POST)) {
would be more appropriate as you are checking if the POST array is actually set and then that it is not empty the && operator is a short circuit operator so if either condition isn't met then the check will fail.
Similarly on your comparisons saying if(!$_POST['email']) { isn't valid because you're effectively asking "if the email part of the post array is not true" where as you need to be asking "if it's not blank and is a valid email address"
You need to be aware of the difference between = == and === operators. You can find some more information here: The 3 different equals
And also the filter_var function here: http://php.net/manual/en/function.filter-var.php
if($_POST['email']!=="" && filter_var($_POST['email'], FILTER_VALIDATE_EMAIL)) {
//all good
} else {
//set your error message
}
you can use regular expressions to validate 'name' see preg_match in the manual http://php.net/manual/en/function.preg-match.php
Aside from all of this if you want to have real time monitoring of the fields and the error messages etc you're going to have to look at incorporating Javascript and using AJAX to communicate with your script and then parse the response back into the appropriate div.
Have a look at Rasmus 30 second AJAX tutorial will give you a starting point for this http://rajshekhar.net/blog/archives/85-Rasmus-30-second-AJAX-Tutorial.html
However it is better practice to do both client and server side validation hope this helps even if it is not a complete answer per sé.

Php contact form open a new page

I'm building a website and have I a php contact form.
Validation of the form and mail() function is working perfectly.
My php file for the form is handler.php.
Now to the problem. When I press the submit button and a error message is coming up, they comes up in a new blank page and that page is the same URL but it added /handler.php in the URL.
What i want to do is make the error messages show up under the form, and if it is no errors I want it to go to my thankyoumessage.html.
This is the php code for the form:
<?php
/*Set the mail of the reciever*/
$myemail = "mymail#example.com";
/*Display error message*/
function show_error($myError)
{
?>
<html>
<body>
<b>Var snäll och rätta till följande fel:</b><br />
<?php echo $myError; ?>
</body>
</html>
<?php
exit();
}
/* Check inputs */
function check_input($data, $problem='error')
{
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
// if ($problem && strlen($data) == 0)
// {
// show_error($problem);
// }
return $data;
}
if (isset($_POST['email']) && isset($_POST['name']) && isset($_POST['message']))
{
/* Check all form inputs using check_input function */
$name = check_input(utf8_decode($_POST['name']));
$subject = check_input(utf8_decode($_POST['subject']));
$email = check_input(utf8_decode($_POST['email']));
$message = check_input(utf8_decode($_POST['message']));
/* If e-mail is not valid show error message */
if (!preg_match("/([\w\-]+\#[\w\-]+\.[\w\-]+)/", $email))
{
show_error("Email adressen är inte giltig...");
echo "<script type='text/javascript'>alert('$message');</script>";
}
/*If name is empty show error message */
if (empty($_POST['name']))
{
show_error("Du måste skriva in ditt namn...");
}
/*If email is empty show error message */
if (empty($_POST['email']))
{
show_error("Du måste skriva in din email...");
}
/*If message is empty show error message */
if (empty($_POST['message']))
{
show_error("Ett meddelande krävs om du önskar att få hjälp av oss...");
}
/* Prepare the message for the e-mail */
$mail =utf8_decode("
Hej!
Ditt kontakt formulär har blivit besvarat av:
Namn: $name
E-mail: $email
Kundens meddelande:
$message
Meddelande slut.
");
echo "Tack för du kontaktar oss! \n Vi återkommer med ett svar så snart som möjligt!";
/* Send the message using mail() function */
mail($myemail, $subject, $mail);
}
else
{
?><span><?php echo "Fyll i alla fälten...";?></span> <?php
}
?>
And this is the Html to the form:
<form class="mt-5 ml-5 mr-5" method="POST" action="handler.php" id="reused_form">
<p id="contactForm" class="h4 text-center mt-5"><strong>Kontakta oss</strong></p>
<!-- input text(Name) -->
<div class="md-form">
<i class="fa fa-user prefix">*</i>
<input type="text" name="name" id="name" class="form-control">
<label>Ditt namn</label>
</div>
<!-- input email -->
<div class="md-form mt-5">
<i class="fa fa-envelope prefix">*</i>
<input type="email" id="name" name="email" id="email" class="form-control validate">
<label data-error="Fel" data-success="Rätt">Din email</label>
</div>
<div class="md-form mt-5">
<i class="fa fa-user prefix"></i>
<input type="text" id="subject" name="subject" class="form-control">
<label>Ämne</label>
</div>
<!-- input message -->
<div class="md-form mt-5">
<i class="fa fa-pencil prefix">*</i>
<textarea type="text" name="message" id="message" maxlength="5000" class="form-control md-textarea" rows="3"></textarea>
<label>Meddelande</label>
</div>
<div class="text-center mt-4 mb-4">
<button class="btn danger-color" name="submit" type="submit">Skicka</button>
</div>
</form>
If you don't want to use AJAX, You can just let the mail() function process the form in the same page as the following :
<?php
// we declare empty error variables
$error = $error_email = $error_name = $error_subject = $error_message = "";
if (isset($_POST['submit']))
{
/* Check all form inputs using check_input function */
$name = check_input(utf8_decode($_POST['name']));
$subject = check_input(utf8_decode($_POST['subject']));
$email = check_input(utf8_decode($_POST['email']));
$message = check_input(utf8_decode($_POST['message']));
/* If e-mail is not valid show error message */
if (!preg_match("/([\w\-]+\#[\w\-]+\.[\w\-]+)/", $email))
{
$error_email = "Email adressen är inte giltig...";
}
/*If name is empty show error message */
if (empty($_POST['name']))
{
$error_name = "Du måste skriva in ditt namn...";
}
/*If email is empty show error message */
if (empty($_POST['email']))
{
$error_email = "Du måste skriva in din email...";
}
/*If message is empty show error message */
if (empty($_POST['message']))
{
$error_message = "Ett meddelande krävs om du önskar att få hjälp av oss...";
}
/// You can add the subject validations here as well
if (empty($_POST['subject']))
{
$error_subject = "Ett meddelande krävs om du önskar att få hjälp av oss...";
}
/* Prepare the message for the e-mail */
$mail =utf8_decode("
Hej!
Ditt kontakt formulär har blivit besvarat av:
Namn: $name
E-mail: $email
Kundens meddelande:
$message
Meddelande slut.
");
if(mail($myemail, $subject, $mail))
{
/// We redirect to the thank you mesage uppon a successful message sending
header("Location:thankyoumessage.html");
}
else
{
// Failure message if the mail() function failed to trigger
$error = "Something wrong !";
}
}
?>
<form class="mt-5 ml-5 mr-5" method="POST" action="" id="reused_form">
<p id="contactForm" class="h4 text-center mt-5"><strong>Kontakta oss</strong></p>
<!-- input text(Name) -->
<div class="md-form">
<i class="fa fa-user prefix">*</i>
<input type="text" name="name" id="name" class="form-control" required >
<label>Ditt namn</label>
</div>
<!-- Error name -->
<div class="text-center mt-4 mb-4">
<?php echo $error_name;?>
</div>
<!-- input email -->
<div class="md-form mt-5">
<i class="fa fa-envelope prefix">*</i>
<input type="email" id="name" name="email" id="email" class="form-control validate" required>
<label data-error="Fel" data-success="Rätt">Din email</label>
</div>
<!-- Error email -->
<div class="text-center mt-4 mb-4">
<?php echo $error_email;?>
</div>
<div class="md-form mt-5">
<i class="fa fa-user prefix"></i>
<input type="text" id="subject" name="subject" class="form-control" required>
<label>Ämne</label>
</div>
<!-- Error subject -->
<div class="text-center mt-4 mb-4">
<?php echo $error_subject;?>
</div>
<!-- input message -->
<div class="md-form mt-5">
<i class="fa fa-pencil prefix">*</i>
<textarea type="text" name="message" id="message" maxlength="5000" class="form-control md-textarea" rows="3" required></textarea>
<label>Meddelande</label>
</div>
<!-- Error message -->
<div class="text-center mt-4 mb-4">
<?php echo $error_message;?>
</div>
<div class="text-center mt-4 mb-4">
<?php echo $error;?>
</div>
<div class="text-center mt-4 mb-4">
<button class="btn danger-color" name="submit" type="submit">Skicka</button>
</div>
</form>
It sounds like you need this in a single page, but your form is directing to a second page (handler.php). You might benefit from having all of the functionality in a single script that loads both the form and handles form submission. The algorithm might go something like this:
$showForm = $showThankYou = false;
$errorMessage = '';
//if form submitted
//check for errors
//if no errors
$showThankYou = true;
//else set error vars appropriately
$errorMessage = '...';
$showForm = true;
// else
$showForm = true;
From this point, you can include both your form and your thank you wrapped in conditionals. You can include your error message in your form html, as it will be blank when the form is first loaded.
if($showForm) {
// form code block
}
if($showThankYou) {
// thank you page
}
It is going to /handler.php because is set on the form action:
<form class="mt-5 ml-5 mr-5" method="POST" action="handler.php" id="reused_form">
If you want to stay on the same page after form submits, you have to leave action empty. Instead, you have to set a conditional that checks if submit is set:
if(isset($_POST['submit']){
include('handler.php');
}
Adding that code below your form will execute the script when the user hits submit (you have to modify it, it has to be an not a button).
That's one way to do it using exclusively PHP. You also can put all the code of sending mail inside a function, and execute it when submit is send:
function sendMail(){
if (isset($_POST['email']) && isset($_POST['name']) && isset($_POST['message']))
{
/* Check all form inputs using check_input function */
$name = check_input(utf8_decode($_POST['name']));
$subject = check_input(utf8_decode($_POST['subject']));
$email = check_input(utf8_decode($_POST['email']));
$message = check_input(utf8_decode($_POST['message']));
/* If e-mail is not valid show error message */
if (!preg_match("/([\w\-]+\#[\w\-]+\.[\w\-]+)/", $email))
{
show_error("Email adressen är inte giltig...");
echo "<script type='text/javascript'>alert('$message');</script>";
}
/*If name is empty show error message */
if (empty($_POST['name']))
{
show_error("Du måste skriva in ditt namn...");
}
/*If email is empty show error message */
if (empty($_POST['email']))
{
show_error("Du måste skriva in din email...");
}
/*If message is empty show error message */
if (empty($_POST['message']))
{
show_error("Ett meddelande krävs om du önskar att få hjälp av oss...");
}
/* Prepare the message for the e-mail */
$mail =utf8_decode("
Hej!
Ditt kontakt formulär har blivit besvarat av:
Namn: $name
E-mail: $email
Kundens meddelande:
$message
Meddelande slut.
");
echo "Tack för du kontaktar oss! \n Vi återkommer med ett svar så snart som möjligt!";
/* Send the message using mail() function */
mail($myemail, $subject, $mail);
}
else
{
?><span><?php echo "Fyll i alla fälten...";?></span> <?php
}
}
Changing the submit code
<?php
include('handler.php');
if(isset($_POST['submit'])){
sendMail();
}
?>
There are any other ways, but this two maybe solve your problem in a way that only uses PHP.
Hope it helps.
PD: You have the same ID for the name and email input.
Sounds like you need JavaScript, since the user will never leave the page. If you make handler.php return some json instead of a page, this will be super easy. First of all, I would put all your HTML in a file called contact.html so you can reference a different page from the one you're currently on. If you add an empty <p class="errorMsg"></p> to the body wherever you want, it will be invisible until there's an error.
Then you can add the below scripts in a file called submitForm.js, adding <script src="submitForm.js"></script> to the head of contact.html.
const formElement = document.querySelector('form')
const formData = new FormData(formElement)
formElement.onsubmit = event => {
event.preventDefault()
fetch('/handler.php', { method: 'POST', body: formData })
.then(response => response.json())
.then(json => {
const errorElement = document.querySelector('errorMsg')
errorElement.textContent = json.errorMsg
if (json.errorMsg !== '') document.location = '/thankyoumessage.html'
})
}
To break it down, fetch is a really easy way to make an ajax request. Your user will stay on the current page, but your code will go out to the URL and get its data for use on the current page. fetch() makes the request, and then() handles it synchronously after it gets the response. Here, I'm chaining two then()s because I need to parse it into json before I can access that data. The last then() is how you would handle the form submission.
Learn more about fetch
Fetch is a new web API that relies on ES6 features and may not be compatible with older browsers. I still encourage you to use it, because even if IE11 support is necessary, all it takes is a polyfill and a syntax converter to do all the work for you.
Now, to make fetch work like this, you'll need to put something in handler.php. You can use all the code in your first snippet, leaving out the HTML. You can return JSON just by building a string and echoing it, no html necessary. You could accomplish that by changing your show_error() function calls to assigning an $errorMsg variable, like this.
if (!preg_match("/([\w\-]+\#[\w\-]+\.[\w\-]+)/", $email))
{
$errorMsg = "Email adressen är inte giltig...";
}
then at the end of the file, instead of HTML you can write the JSON string like so.
echo '{ "errorMsg" : "' . $errorMsg . '" }';
Now, if your form still hit that page with an Email error for example, you would see this:
{ "errorMsg" : "Email adressen är inte giltig..." }
... Obviously you don't want to see that, but your JavaScript can see that without your user looking at it, and the JavaScript knows exactly what to do with that data, like we saw above. Then you can add as many things as you want to that JSON, so your live JavaScript can do other things with it.
Learn more about JSON

Form is submitting to another page without validation in php

This is the code i have used for online Registration
Validation is not working when i submit it another page,form is submitting to another page without any validation.i just need too know how to submit it with validation, can some one help out
<?php
// define variables and set to empty values
$nameErr = $cnameErr = $mobilenoErr = $emailErr = $cityErr= $postalcodeErr = $addressErr = "";
$name = $cname = $mobileno = $email = $city= $postalcode = $address = "";
if ($_SERVER["REQUEST_METHOD"] == "POST") {
if (empty($_POST["name"])) {
$nameErr = "Name is required";
} else {
$name = test_input($_POST["name"]);
// check if name only contains letters and whitespace
if (!preg_match("/^[a-zA-Z ]*$/",$name)) {
$nameErr = "Only letters and white space allowed";
}
}
if (empty($_POST["cname"])) {
$cnameErr = "Company Name is required";
} else {
$cname = test_input($_POST["cname"]);
}
if (empty($_POST["mobileno"])) {
$mobilenoErr = "Mobile Number is required";
}else {
$mobileno = test_input($_POST["mobileno"]);
// check if name only contains letters and whitespace
if (!preg_match("/^[789][0-9]{9}$/",$mobileno)) {
$mobilenoErr = "Not A Valid Number";
}
}
if (empty($_POST["email"])) {
$emailErr = "Email is required";
} else {
$email = test_input($_POST["email"]);
// check if e-mail address is well-formed
if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
$emailErr = "Invalid email format";
}
}
if (empty($_POST["city"])) {
$cityErr = "City is required";
} else {
$city = test_input($_POST["city"]);
// check if name only contains letters and whitespace
if (!preg_match("/^[a-zA-Z ]*$/",$city)) {
$cityErr = "Only letters and white space allowed";
}
}
if (empty($_POST["postalcode"])) {
$postalcodeErr = "Postal Code is required";
} else {
$postalcode = test_input($_POST["city"]);
}
if (empty($_POST["address"])) {
$addressErr = "Address is required";
} else {
$address = test_input($_POST["address"]);
}
}
function test_input($data) {
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
?>
<div class="gridContainer clearfix">
<div id="div1" class="fluid"><!-- header ends here-->
<div id="header" class="fluid">
<div class="fluid logo_container zeroMargin_tablet">
<div class="fluid logo_mvc"></div>
<!-- logo_mvc ends here-->
<div class="fluid logo_gsm"></div>
<!-- logo_gsm ends here-->
</div>
<!-- logo_container ends here-->
</div>
<div class="fluid imageslide zeroMargin_desktop">
<div class="fluid imageslide_gs zeroMargin_desktop"></div>
<!-- imageslide_gs ends here-->
<div class="fluid imageslide_content">
<h1>IP Product Introduction and VoIP PBX
Appliance Training Day # Toronto</h1>
</div><!-- imageslide_content ends here-->
<div class="fluid imageslide_product"></div>
<!-- imageslide_product ends here-->
</div><!-- imageslide ends here-->
<div class="fluid content">
<div class="fluid content_det">
<h3>Event information</h3>
<p>Please join us at the Fairfield Inn & Suites Toronto Airport where Grandstream will offer four different sessions during the day. </p>
<h3>Introduction to Grandstream IP products</h3>
<p><b>8:45am - 10:15am</b><br/>
Introduction to Grandstream, and basic information on Grandstream products including ATAs, gateways, routers and telephones. </p>
<h3>Introduction to IP cameras IP and Surveillance products</h3>
<p><b>12:45pm - 2:15pm</b><br/>
Basic information on IP cameras and surveillance products, and the introduction of the brand new GVR3550 Network Video Recorder. </p>
<h3>Advanced Technical Training for UCM VoIP PBX's</h3>
<p><b>2:30pm - 4:30pm</b><br/>
This session will focus on the advanced features of the UCM series, including the new features of the upcoming software and the brand new UCM6510 VoIP PBX for T1 networks. </p>
</div><!-- content_det ends here--><div class="fluid contet_form">
<h2>Register Now</h2>
<form method="post" action="Submission.php">
<div class="fluid div_form"><label><b>First name *:</b></label>
<input type="text" size="20px" name="name" placeholder="Enter Your Name Here" value="<?php echo $name; ?>"/><span class="error"><?php echo $nameErr;?></span>
</div>
<div class="fluid div_form"><label><b>Company Name *:</b></label>
<input type="text" size="20px" name="cname" placeholder="Enter Your Company Name Here" value="<?php echo $cname; ?>"/><span class="error"><?php echo $cnameErr;?></span></div>
<div class="fluid div_form"><label><b>Mobile Number *:</b></label>
<input type="text" size="20px" name="mobileno" placeholder="Enter Your Mobile Number Here" value="<?php echo $mobileno; ?>"/><span class="error"><?php echo $mobilenoErr?></span>
</div>
<div class="fluid div_form"><label><b>Email Id *:</b></label>
<input type="email" size="20px" name="email" placeholder="Enter Your Email Id Here" value="<?php echo $email; ?>"/><span class="error"><?php echo $emailErr?></span></div>
<div class="fluid div_form"><label><b>City *:</b></label>
<input type="text" size="20px" name="city" placeholder="Enter Your City Name Here" value="<?php echo $city;?>"/><span class="error"><?php echo $cityErr?></span></div>
<div class="fluid div_form"><label><b>Postal Code *:</b></label>
<input type="text" size="20px" name="postalcode" placeholder="Enter Postal Code Here" value="<?php echo $postalcode; ?>"/><span class="error"><?php echo $postalcodeErr?></span>
</div>
<div class="fluid div_form"><label><b>Address *:</b></label>
<input type="text" size="20px" name="address" placeholder="Enter Address Here" value="<?php echo $address; ?>"/><span class="error"><?php echo $addressErr?></span></div>
<button name="submit">Submit</button>
</form>
</div><!-- contet_form ends here-->
</div><!-- content ends here-->
</div><!-- div1 ends here-->
</div>
</body>
The validation has to happens when the request reaches the server. Your flow is like:
form displayed in browser -> user clicks submit -> data submitted to Submission.php -> validation should happen here.
Put your validation code in Submission.php.
To me it seems you are new to PHP form handling. For beginners reinventing the wheel and is dangerous as it's so easy to open up security flaws in your script. Use a framework or CMS that can handle forms for you (e.g., WordPress and Contact Form 7 or just use something easy as Zebra Form or something complete like CakePHP, Laravel or Symfony.
Just don't do everything yourself unless you really know what you are doing. It might take some time to get started, but it will definitely pay off in the long run.
Carefully check your action in form attribute. If you mention page name in form attribute then it will submit another page without validation. If you want validation in same page then remove page name from your action in form attribute. Other wise put validation checking in another page, which is mention in your action in form attribute.

PHP form processing a pre-filled form from a query string

I'm trying to get a form pre-filled using a query string and let the user make any necessary changes then press submit and have the form process and send an email to an administrator for doing whatever it is they need to do with the information.
I'm using PHP to populate the form and I started with a tutorial from NetTuts for the email form processing because it did validation inline. Hopefully validation isn't necessary because all the fields are pre-filled but I wanted to have the form check just to make sure the user doesn't clear a field before submitting the form. I'm at a loss as to why the form won't process correctly.
The only changes between my form and the tutorial are in variable names, the inclusion and some $_GET superglobals to grab the form data from the query string, and the use of echo to fill out the form from the $_GET superglobals instead of the session data should the user submit the form without filling everything out. Everything else has been copied verbatim from the tutorial.
Any help solving this problem, even if it's rethinking how I might go about doing this, would be much appreciated.
Below is the code for the form page and the processing page.
Form Page:
<?php
session_start();
// site root folder
$root_folder = "/meetingplannersignup";
//get values of displayed form fields from URL
$FirstName= $_GET['FirstName'];
$LastName = $_GET['LastName'];
$Organization = $_GET['Organization'];
$EmailAddress = $_GET['EmailAddress'];
$Phone = $_GET['Phone'];
$EventType = $_GET['EventType'];
$EventName = $_GET['EventName'];
$EventLocation = $_GET['EventLocation'];
$HotelName = $_GET['HotelName'];
$EventStart = $_GET['EventStart'];
$EventEnd = $_GET['EventEnd'];
// get values of hidden form fields from URL
$ExtReferenceID = $_GET['ExtReferenceID'];
$City = $_GET['City'];
$State = $_GET['State'];
$ZipCode = $_GET['ZipCode'];
$CountryCode = $_GET['CountryCode'];
?>
<!DOCTYPE html>
<!--[if IE 8]><html class="no-js lt-ie9" lang="en" > <![endif]-->
<!--[if gt IE 8]><!--><html class="no-js" lang="en" > <!--<![endif]-->
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width">
<title>Simplify Event Management with GroupMAX</title>
<link rel="stylesheet" href="<?php echo $root_url ?>/assets/css/bootstrap.css">
</head>
<body>
<div class="container">
<!-- begin main nav -->
<nav class="navbar navbar-static-top navbar-inverse" role="navigation">
<!-- Brand and toggle get grouped for better mobile display -->
<div class="navbar-header">
<button type="button" class="navbar-toggle" data-toggle="collapse" data-target=".navbar-main-collapse">
<span class="sr-only">Toggle navigation</span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
</button>
</div>
<!-- Collect the nav links, forms, and other content for toggling -->
<div class="collapse navbar-collapse navbar-main-collapse">
<ul class="nav navbar-nav">
<li class="active">home</li>
<li>fill out form</li>
</ul>
</div><!-- /.navbar-collapse -->
</nav>
<!-- end main nav -->
<div class="row">
<div class="col-lg-12">
<h1>Simplify Event Management with GroupMAX</h1>
<h3>Impress Your Attendees. Optimize Your Event.</h3>
<hr />
</div>
</div>
<div class="row">
<div class="col-lg-6">
<h4>Included Features are:</h4>
<ul>
<li><strong>Event Booking Websites – </strong>Passkey’s award winning booking website allows for personalized hotel reservation website where attendees can make, modify or cancel their hotel bookings directly into that group's contracted block.</li>
<li><strong>Integrated with Event Registration - </strong>RegLink™ is an integration technology that can link any online planner registration solution to Passkey's best-in-class hotel reservation system, allowing meeting planners to integrate hotel reservations directly into their event registration process.</li>
<li><strong>Event Dashboard – </strong>With Event Dashboard Planners can track their events, manage their lists and monitor reservations anytime online. With Passkey’s LiveView Dashboards, meeting planners can get an instant snapshot of their event in a fun, interactive environment. </li>
<li><strong>SmartAlerts™ - </strong>Automatic e-mails containing vital event information that are automatically sent out to a list of recipients at specific intervals or critical event milestones.</li>
</ul>
</div>
<div class="col-lg-6">
<div class="row">
<div class="col-lg-12">
<!-- begin error processing -->
<div class="well">
<?php
//init variables
$cf = array();
$sr = false;
if(isset($_SESSION['cf_returndata'])){
$cf = $_SESSION['cf_returndata'];
$sr = true;
}
?>
<div id="errors" class="alert alert-danger<?php echo ($sr && !$cf['form_ok']) ? ' show_alert' : ''; ?>">
<p>There were some problems with your form submission:</p>
<ul>
<?php
if(isset($cf['errors']) && count($cf['errors']) > 0) :
foreach($cf['errors'] as $error) :
?>
<li><?php echo $error ?></li>
<?php
endforeach;
endif;
?>
<?php
//init variables
$cf = array();
$sr = false;
if(isset($_SESSION['cf_returndata'])){
$cf = $_SESSION['cf_returndata'];
$sr = true;
}
?>
</ul>
</div>
<p id="success" class="alert alert-success<?php echo ($sr && $cf['form_ok']) ? ' show_alert' : ''; ?>">Thanks for your message! We will get back to you ASAP!</p>
<!-- end error processing -->
<!-- begin form -->
<fieldset>
<legend>Your Information</legend>
<p>Please review the pre-filled information and correct any inaccurate information prior to submitting the form.</p>
<form method="post" action="process.php">
<div class="form-group">
<label>First Name</label>
<input type="text" class="form-control" id="FirstName" value="<?php echo ($sr && !$cf['form_ok']) ? $cf['posted_form_data']['FirstName'] : '' ?><?php echo $FirstName; ?>">
</div>
<div class="form-group">
<label>Last Name</label>
<input type="text" class="form-control" id="LastName" value="<?php echo $LastName; ?>">
</div>
<div class="form-group">
<label>Company/Organization</label>
<input type="text" class="form-control" id="Organization" value="<?php echo $Organization; ?>">
</div>
<div class="form-group">
<label>Email Address</label>
<input type="text" class="form-control" id="EmailAddress" value="<?php echo $EmailAddress; ?>">
</div>
<div class="form-group">
<label>Phone Number</label>
<input type="text" class="form-control" id="Phone" value="<?php echo $Phone; ?>">
</div>
<div class="form-group">
<label>Event Type</label>
<input type="text" class="form-control" id="EventType" value="<?php echo $EventType; ?>">
</div>
<div class="form-group">
<label>Event Name</label>
<input type="text" class="form-control" id="EventName" value="<?php echo $EventName; ?>">
</div>
<div class="form-group">
<label>Event Location</label>
<input type="text" class="form-control" id="EventLocation" value="<?php echo $EventLocation; ?>">
</div>
<div class="form-group">
<label>Hotel Name</label>
<input type="text" class="form-control" id="HotelName" value="<?php echo $HotelName; ?>">
</div>
<div class="form-group">
<label>Start/Arrival Date</label>
<input type="text" class="form-control" id="EventStart" value="<?php echo $EventStart; ?>">
</div>
<div class="form-group">
<label>End Date</label>
<input type="text" class="form-control" id="EventEnd" value="<?php echo $EventEnd; ?>">
</div>
<hr />
<input type="submit" value="Submit" class="btn btn-primary" />
<!--hidden fields-->
<input type="hidden" id="ExtReferenceID" value="<?php echo $ExtReferenceID; ?>">
<input type="hidden" id="City" value="<?php echo $City; ?>">
<input type="hidden" id="State" value="<?php echo $State; ?>">
<input type="hidden" id="ZipCode" value="<?php echo $ZipCode; ?>">
<input type="hidden" id="CountryCode" value="<?php echo $CountryCode; ?>">
</form>
<?php unset($_SESSION['cf_returndata']); ?>
</fieldset>
</div>
<!-- end form -->
</div>
</div>
</div>
</div>
</div>
</body>
</html>
Processing Page:
<?php
if( isset($_POST) ){
//form validation vars
$formok = true;
$errors = array();
//submission data
$ipaddress = $_SERVER['REMOTE_ADDR'];
$date = date('d/m/Y');
$time = date('H:i:s');
//form data
$FirstName = $_POST['FirstName'];
$LastName = $_POST['LastName'];
$Organization = $_POST['Organization'];
$EmailAddress = $_POST['EmailAddress'];
$Phone = $_POST['Phone'];
$EventType = $_POST['EventType'];
$EventName = $_POST['EventName'];
$EventLocation = $_POST['EventLocation'];
$HotelName = $_POST['HotelName'];
$EventStart = $_POST['EventStart'];
$EventEnd = $_POST['EventEnd'];
// hidden form fields
$ExtReferenceID = $_POST['ExtReferenceID'];
$City = $_POST['City'];
$State = $_POST['State'];
$ZipCode = $_POST['ZipCode'];
$CountryCode = $_POST['CountryCode'];
//validate form data
//validate First Name is not empty
if(empty($FirstName)){
$formok = false;
$errors[] = "You have not entered a First Name";
//validate Last Name is not empty
} elseif (empty($LastName)){
$formok = false;
$errors[] = "You have not entered a Last Name";
//validate Company/Organization is not empty
} elseif (empty($Organization)){
$formok = false;
$errors[] = "You have not entered a Company or organization";
//validate email address is not empty
} elseif (empty($EmailAddress)){
$formok = false;
$errors[] = "You have not entered an email address";
//validate email address is valid
} elseif (!filter_var($EmailAddress, FILTER_VALIDATE_EMAIL)){
$formok = false;
$errors[] = "You have not entered a valid Email Address";
//validate Last Name is not empty
} elseif (empty($Phone)){
$formok = false;
$errors[] = "You have not entered a Phone Number";
//validate Last Name is not empty
} elseif (empty($EventType)){
$formok = false;
$errors[] = "You have not entered an Event Type";
//validate Last Name is not empty
} elseif (empty($EventName)){
$formok = false;
$errors[] = "You have not entered an Event Name";
//validate Last Name is not empty
} elseif (empty($EventLocation)){
$formok = false;
$errors[] = "You have not entered an Event Location";
//validate Last Name is not empty
} elseif (empty($HotelName)){
$formok = false;
$errors[] = "You have not entered a Hotel Name";
//validate Last Name is not empty
} elseif (empty($EventStart)){
$formok = false;
$errors[] = "You have not entered an Event Start Date";
//validate Last Name is not empty
} elseif (empty($EventEnd)){
$formok = false;
$errors[] = "You have not entered an Event End Date";
}
//send email if all is ok
if($formok){
$headers = "From: meetingplannersignup#passkey.com" . "\r\n";
$headers .= 'Content-type: text/html; charset=iso-8859-1' . "\r\n";
$emailbody = "<p>You have recieved a new meeting planner signup registration:</p>
<p><strong>First Name: </strong> {$FirstName}</p>
<p><strong>Last Name: </strong> {$LastName}</p>
<p><strong>Company/Organization: </strong> {$Organization}</p>
<p><strong>Email Address: </strong> {$EmailAddress}</p>
<p><strong>Phone: </strong> {$Phone}</p>
<hr />
<p><strong>Event Type: </strong> {$EventType}</p>
<p><strong>Event Name: </strong> {$EventName}</p>
<p><strong>Event Location: </strong> {$EventLocation}</p>
<p><strong>Hotel Name: </strong> {$HotelName}</p>
<p><strong>Event Start Date: </strong> {$EventStart}</p>
<p><strong>Event End Date: </strong> {$EventEnd}</p>
<hr />
<p><strong>Reference ID: </strong> {$ExtReferenceID}</p>
<p><strong>City: </strong> {$City}</p>
<p><strong>State: </strong> {$State}</p>
<p><strong>Zip Code: </strong> {$ZipCode}</p>
<p><strong>Country Code: </strong> {$CountryCode}</p>
<hr />
<p>This message was sent from the IP Address: {$ipaddress} on {$date} at {$time}</p> ";
mail("stuart#monderer.com","Meeting Planner Signup",$emailbody,$headers);
}
//what we need to return back to our form
$returndata = array(
'posted_form_data' => array(
'FirstName' => $FirstName,
'LastName' => $LastName,
'EmailAddress' => $EmailAddress,
'Organization' => $Organization,
'Phone' => $Phone,
'EventType' => $EventType,
'EventName' => $EventName,
'EventLocation' => $EventLocation,
'HotelName' => $HotelName,
'EventStart' => $EventStart,
'EventEnd' => $EventEnd,
'ExtReferenceID' => $ExtReferenceID,
'City' => $City,
'State' => $State,
'ZipCode' => $ZipCode,
'CountryCode' => $CountryCode
),
'form_ok' => $formok,
'errors' => $errors
);
//if this is not an ajax request
if(empty($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) !== 'xmlhttprequest'){
//set session variables
session_start();
$_SESSION['cf_returndata'] = $returndata;
//redirect back to form
header('location: ' . $_SERVER['HTTP_REFERER']);
}
}
Several problems:
1. isset($_POST) will always be true
In your processing page you check for:
if( isset($_POST) )
This will always evaluate to true even if $_POST is empty. You should check for a specific field to try and guess is the form was submitted
2. You use id instead of name
The form values that are sent via POST are identified via their name, not via their id. In the HTML you can keep the id attribute but for each field that is to be POSTed you must add a name attribute:
<input type="text" class="form-control" name="LastName" id="LastName" value="<?php echo $LastName; ?>">
$_POST['LastName'] is empty if you only identify your form control with an id.
I haven't checked the rest but you should try to fix those points first.

Categories