validating and submitting with 'if' and 'else' using PHP - php

This code is supposed to check to see if any fields are blank or invalid, if they are, it will turn them red. if all is ok then it will send to the database.
The problem is, if the last 'if' is not met, then the 'else' will fire.
This means as long as a valid email address is entered the form will submit, even if other fields are blank.
How can I make so that all requirements must be met for the form to submit
if(empty($_POST['company'])) {
echo '<script type="text/javascript">
$(document).ready(function() {
$("#companyForm").animate({backgroundColor:"#ffbfbf"},500);
});
</script>
';
}
if(empty($_POST['name'])) {
echo '<script type="text/javascript">
$(document).ready(function() {
$("#nameForm").animate({backgroundColor:"#ffbfbf"},500);
});
</script>
';
}
if(empty($_POST['email'])) {
echo '<script type="text/javascript">
$(document).ready(function() {
$("#emailForm").animate({backgroundColor:"#ffbfbf"},500);
});
</script>
';
}
if(filter_var($email, FILTER_VALIDATE_EMAIL) === FALSE){
echo '<script type="text/javascript">
$(document).ready(function() {
$("#emailForm").animate({backgroundColor:"#ffbfbf"},500);
});
</script>
';
}
else {
//submits to database...
}

You can use a flag as:
$isValid = true;
if(empty($_POST['company'])) {
$isValid = false;
// your echo
}
Similarly add the $isValid = false; for all the other if bodies.
Finally remove your else part and replace it with:
if($isValid) {
// submit to DB.
}

you either can use else if, but then you won't see your "red" for all wrong fields but only for the first that failed validation.
like so:
if() {
} elseif() {
} else {
...
}
or you could set something to $error=false at the beginning, and set error to true inside the if controlled code and the submission to database checks if error is still false...

<?php
$error = 1;
if(empty($_POST['company'])) {
echo '<script type="text/javascript">
$(document).ready(function() {
$("#companyForm").animate({backgroundColor:"#ffbfbf"},500);
});
</script>
';
$error = 0;
}
if(empty($_POST['name'])) {
echo '<script type="text/javascript">
$(document).ready(function() {
$("#nameForm").animate({backgroundColor:"#ffbfbf"},500);
});
</script>
';
$error = 0;
}
if(empty($_POST['email'])) {
echo '<script type="text/javascript">
$(document).ready(function() {
$("#emailForm").animate({backgroundColor:"#ffbfbf"},500);
});
</script>
';
$error = 0;
}
if(filter_var($email, FILTER_VALIDATE_EMAIL) === FALSE){
echo '<script type="text/javascript">
$(document).ready(function() {
$("#emailForm").animate({backgroundColor:"#ffbfbf"},500);
});
</script>
';
$error = 0;
}
if($error == 1) { //submits to database...
}
?>

There is a far better way of doing this instead of repeating your own code for each POST variable, which is not efficient.
// loop through all submitted fields
foreach( $_POST as $key => $value){
// see if the field is blank
if($value=="" || $value is null){
// if blank output highlighting JS
echo "<script type='text/javascript'>
$(document).ready(function() {
$('#".$key."Form').animate({backgroundColor:'#ffbfbf'},500);
});
</script>";
// variable to value showing form is invalid in some way
$invalid=1;
}
}
if(filter_var($email, FILTER_VALIDATE_EMAIL) === FALSE){
echo '<script type="text/javascript">
$(document).ready(function() {
$("#emailForm").animate({backgroundColor:"#ffbfbf"},500);
});
</script>
';
$invalid= 1;
}
// if form invalid variable not set, submit to DB
if($invalid!=1){
// submit to DB
}
If you want to be super efficient you can simply use:
// search for any values that are null (empty fields)
$invalid_fields=array_keys($_POST, null);
// you may need to use $invalid_fields=array_keys($_POST, "");
// if there are any results from this search, loop through each to highlight the field
if($invalid_fields){
foreach( $invalid_fields as $key => $value){
echo "<script type='text/javascript'>
$(document).ready(function() {
$('#".$value."Form').animate({backgroundColor:'#ffbfbf'},500);
});
</script>";
}
$error = 1;
}
if(filter_var($email, FILTER_VALIDATE_EMAIL) === FALSE){
echo '<script type="text/javascript">
$(document).ready(function() {
$("#emailForm").animate({backgroundColor:"#ffbfbf"},500);
});
</script>
';
$error = 1;
}
if($error!=1){
// submit to DB
}

Introduce a Variable $sendToDb and initialy set it to (bool) true. If any of your checks fails, set this variable to false.
Then rewrite the else-Part and do a
if ($sendToDb) {
/* Your Db-Write code */
}

Take a flag variable and check like this
$flag=0;
if(empty($_POST['company'])) {
echo '<script type="text/javascript">
$(document).ready(function() {
$("#companyForm").animate({backgroundColor:"#ffbfbf"},500);
});
</script>
';
$flag=1;
}
if(empty($_POST['name'])) {
echo '<script type="text/javascript">
$(document).ready(function() {
$("#nameForm").animate({backgroundColor:"#ffbfbf"},500);
});
</script>
';
$flag=1;
}
if(empty($_POST['email'])) {
echo '<script type="text/javascript">
$(document).ready(function() {
$("#emailForm").animate({backgroundColor:"#ffbfbf"},500);
});
</script>
';
$flag=1;
}
if(filter_var($email, FILTER_VALIDATE_EMAIL) === FALSE){
echo '<script type="text/javascript">
$(document).ready(function() {
$("#emailForm").animate({backgroundColor:"#ffbfbf"},500);
});
</script>
';
$flag=1;
}
if ($flag == 0)
{//submit to database
}

You really shouldn't be mixing server-side code (PHP) with client-side code (JavaScript).
Validate on the server side first. Then add validation on the client side. The reason being, if your user has JavaScript enabled then they'll get the error messages before the form submits. If they have JavaScript disabled, then your PHP script will throw the errors. Something like the following script:
<?php
if (isset($_POST['submit'])) {
$errors = array();
// do server-side validation
if ($_POST['fieldName'] == '') {
$errors['fieldName'] = 'fieldName is required';
}
if (count($errors) == 0) {
// save your record to the database or whatever
}
}
And then the following template:
<style>
.error { border-color: red; }
</style>
<script>
$(document).ready(function() {
$('form#yourFormId').submit(function() {
var errors = null;
if (errors.length > 0) {
return false;
}
});
});
</script>
<form action="yourScript.php" method="post" id="yourFormId">
<input type="text" name="fieldName" value="" id="id"<?php if (in_array('fieldName', $errors)) echo ' class="error"'; ?>>
<input type="submit" name="submit">
</form>
This will apply a class of .error to any invalid form fields, first by JavaScript and then server-side.

Related

How to jQuery Validate the ReCaptcha?

Recaptcha form is like this:
<script type="text/javascript">
var RecaptchaOptions = {"theme":"red","lang":"en"};
</script><script type="text/javascript" src="https://www.google.com/recaptcha/api/challenge?k=6LeThAsTAAAAAKYRjSpA8XZ1s4izK65hYr9ulCiD">
</script><noscript>
<iframe src="https://www.google.com/recaptcha/api/noscript?k=6LeThAsTAAAAAKYRjSpA8XZ1s4izK65hYr9ulCiD"
height="300" width="500" frameborder="0"> </iframe><br>
<textarea name="recaptcha_challenge_field" rows="3" cols="40">
</textarea>
<input type="hidden" name="recaptcha_response_field"
value="manual_challenge">
</noscript>
and validator of ZF2 for ReCaptcha is like this:
$recaptcha = new ZendService\ReCaptcha\ReCaptcha(PUB_KEY, PRIV_KEY);
$html = $recaptcha->getHTML();
$result = $recaptcha->verify($_POST['recaptcha_challenge_field'], $_POST['recaptcha_response_field']);
if (!$result->isValid()) {
// invalid
} else {
// valid
}
is it possible to validate it remotely like this: https://jqueryvalidation.org/remote-method
I tried below in remote php file and it doesn't work:
$recaptcha = new ZendService\ReCaptcha\ReCaptcha(PUB_KEY, PRIV_KEY);
$result = $recaptcha->verify($_GET['recaptcha_challenge_field'], $_GET['recaptcha_response_field']);
if (!$result->isValid()) {
echo json_encode(false);
} else {
echo json_encode(true);
}
and js itself is:
$().ready(function() {
$("#contact").validate({
rules: {
recaptcha_response_field: {
required: true,
remote: "json.php"
}
}
});
});
is it possible at all or I did something wrong?
try this function to validate recaptcha
var grecaptchaId;
var onloadCallback = function () {
grecaptchaId = grecaptcha.render('grecaptcha', {
'sitekey': 'xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx',
'callback': function (response) {
$("#grecaptcha_error").text('');
}
});
};
function ValidateRecaptcha() {
var x;
x = grecaptcha.getResponse(grecaptchaId);
if (x != "") {
$("#grecaptcha_error").text('');
return true;
}
else {
$("#grecaptcha_error").text('The captcha is required and can\'t be empty');
return false;
}
}

How to validate users input before action

I'm really new in internet languages and i try to figure out how it's possible to validate the users input before method call but i just can't make it work yet.
<html>
<head>
</head>
<body>
<?php
$grade = "";
if ($_SERVER["REQUEST_METHOD"] == "POST")
{
$returned = test_input($_POST["grade"]);
if(!$returned) ?
}
function test_input($data)
{
if ( !is_numeric($data) || $data>100 || $data<0 )
{
$data = "";
echo 'The input should be a number between 0 and 100 ';
echo "<br>";
echo 'Try again';
return false;
}
return true;
}
?>
<form action = "file_1_2.php" method = "post">
Grade: <input type="text" name="grade">
</form>
</body>
</html>
Further to my and other comments, your function has incorrect if clauses, specifically your greater than, less than. I would suggest not echoing any strings from it otherwise you have a limited-use function.
function input_valid($data = false)
{
if(empty($data))
return false;
elseif($data && !is_numeric($data))
return false;
else
return (($data <= 100) && ($data > 0));
}
if(isset($_POST["grade"])) {
if(input_valid($_POST["grade"])) {
// Do stuff.
}
else {
echo 'Invalid input. Must be a number between 1 and 100.';
}
}
NOTE: I feel it's important to re-iterate my comment above which is you SHOULD NOT rely solely on client-side validation. The user can turn it off, then you have no validation. Client-side validation should be considered only as a "user experience" feature, not a "security" feature.
You can try using jquery
<form action = "file_1_2.php" method = "post">
Grade: <input type="text" name="grade" class="grade" onkeyup="">
</form>
<script type='text/javascript' src="https://code.jquery.com/jquery-2.2.0.min.js"></script>
<script>
$(function(){
$('input.grade').bind("keyup change", function(){
validateGrade( $(this).val() );
});
});
function validateGrade(g){
if(g>100 || g<0){
alert('The input should be a number between 0 and 100');
}
}
</script>

Open new window for multiple edit records

What I have here is a table that displays record from my database. It also generates dynamic checkboxes along with the fetched record. What I need to do is to open a new window using window.open, instead for the page to go to editor.php. Any help will be gladly appreciated.
MySQLi Query
while ($row = $result1->fetch_assoc()) {
<td><input name="checkbox[]" type="checkbox" id="checkbox[]" value="' . $row['id'] . '"'.($row['pr'] == ""?"disabled ":"").' style="cursor:pointer;" class="checkbox"></td>
}
Javascript
<script type="text/javascript" language="javascript">
function setCheckboxes3(act) {
$('.checkbox').not(':disabled').prop('checked', act == 1 ? true : false);
//or $('.checkbox:not(:disabled)').prop('checked', act == 1 ? true : false)
}
</script>
<script>
jQuery(function ($) {
$('a.button.edit, a.button.remove').click(function () {
if ($('input[name="checkbox[]"]:checked').length == 0) {
return;
}
if ($(this).hasClass('edit')) {
if (!confirm('Edit this Record(s)?')) {
return
}
} else {
if (!confirm('WARNING !!! All Purchase Order that included in this Record(s) will be deleted.')) {
return
}
}
var frm = document.myform;
if ($(this).hasClass('edit')) {
frm.action = 'editpr.php';
}
if ($(this).hasClass('remove')) {
if (!confirm('Are you sure want to continue?')) {
return
}
}
frm.submit();
})
})
</script>
HTML
<a class="button edit" style="cursor:pointer;"><span><b>Edit</b></span></a>

echo out php variable in jQuery

this is changepassword.php file
<?php
include 'core/init.php';
if (empty($_POST) === false) {
if (md5($_POST['current_password']) === $user_data['password']) {
} else {
$errors[] = 'Your current psasword is incorrect';
}
}
if (empty($_POST) === false && empty($errors) === true) {
change_password($session_user_id, $_POST['password']);
} else if (empty($errors) === false) {
$error = output_errors($errors);
this variable
}
?>
this is the jQuery file
$('#save_pass').click(function(){
var current_password = $('#current').val();
var password = $('#new').val();
var password_again = $('#confirm').val();
if ((password == password_again) && (password.length >= 8)) {
$.post('changepassword.php', {current_password: current_password, password: password, password_again: password_again });
$('#show').html('password changed').fadeIn(500).delay(2000).fadeOut(500);
} else if ((current_password ==0) || (password_again.length == 0) || (password.length == 8)) {
$('#show').html('all fields are required').fadeIn(500).delay(2000).fadeOut(500);
} else {
$('#show').html('your password must be at least 8 characters').fadeIn(500).delay(2000).fadeOut(500); }
$('#current').val(null);
$('#new').val(null);
$('#confirm').val(null);
});
i want to echo out $error variable when a user enters an incorrect password and click on the change password button with id="#save_pass"
You cannot echo php variables within a javascript file. Instead, put the javascript in your php file and echo it there - eg:
<script>
function something() {
alert('<?php echo $error; ?>');
}
</script>
In order to get back the errors from your $.post() ajax call, you need to echo $errors in your php script. Then add a success/done function to your $.post():
$.post('changepassword.php', {current_password: current_password ...})
.done(function (data) {
alert(data);
}
This should be the basics for getting back the raw echo data, but look at $.post documentation for more guidance on how to refine this.

Ajax + PHP validation and call Javascript function inside PHP validation

Basically, I'm trying to call a Javascript function inside a PHP script when using Ajax.
JavaScript:
<script type="text/javascript">
function Validate() {
hr = new XMLHttpRequest();
name = document.getElementById('name').value;
hr.open('POST', 'validator.php', true);
hr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
hr.onreadystatechange = function() {
if ( hr.readyState == 4 && hr.status == 200 ) {
document.getElementById('message').innerHTML = hr.responseText;
}
}
hr.send('name=' + name);
}
function disable() {
document.getElementById('message').innerHTML = '';
}
</script>
HTML:
<div id="message"></div>
Name: <input type="text" id="name /">
<input type="button" onclick="Validate();" value="Validate" />
PHP:
<?php
$name = $_POST['name'];
if ( !empty( $name ) ) {
if ( $name == 'Tom' ) {
echo "<script>alert('Hello Tom, Welcome Back')</script>";
} else {
echo 'You are not Tom';
}
} else {
echo 'Please enter a name.';
}
?>
Everything works fine except calling the Javascript function inside PHP echo <script>alert()</script>
What I think the problem here is because I declared hr.responseText, as a result, the javascript I want to show has returned into text. But what should I do to solve this problem?
Any help would be appreciated.
Try changing your echo from "<script>alert('Hello Tom, Welcome Back')</script>";
to just 'Hello Tom, Welcome Back';
Then in your javascript you can call alert(hr.responseText);
You will have to change your javascript to check for what is returned so you know to call either the alert or the
document.getElementById('message').innerHTML = hr.responseText;
EDIT: I will add all the changed code...
<?php
$name = $_POST['name'];
if(!empty($name)){
if($name == 'Tom'){
echo 'Hello Tom, Welcome Back';
}else{
echo 'You are not Tom';
}
}else{
echo 'Please enter a name.';
}
?>
Javascript
<script type="text/javascript">
function Validate(){
hr = new XMLHttpRequest();
name = document.getElementById('name').value;
hr.open('POST', 'validator.php', true);
hr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
hr.onreadystatechange = function(){
if(hr.readyState == 4 && hr.status == 200){
response = hr.responseText.replace(/^\s+|\s+$/g,''); //remove whitespace so you can compare
if (response == ("You are not Tom") || response == ("Please enter a name."))
{
document.getElementById('message').innerHTML = hr.responseText;
}
else {
alert(hr.responseText);
}
}
}
hr.send('name=' + name);
}
function disable(){
document.getElementById('message').innerHTML = '';
}
</script>
Try this:
function do_alert($msg){
echo '<script type="text/javascript">alert("' . $msg . '"); </script>';
}
if(!empty($name)){
if($name == 'Tom'){
do_alert("You are tom");
}else{
do_alert("You are not tom");
}
}else{
echo 'Please enter a name.';
}
You didn't tag jQuery, but if you are using it, $.getScript might be what you want.
Aside from that, it might be better to build the script into your original document, and then execute this or that function based on the response text.

Categories