CCJavascript Return True Page Refresh Error - php

I am writing a form validation code in PHP. Below is the code.
the element with id #questionSubmit is a form with 6 text fields (code, question, answer, option1, option2, option3, option4, option5) and a submit button.
<form id="createQuestionForm" action="" method="POST">
Question Code: <input id="code" class="createQuestionTextBox1" type="text" name="questionCode">
Question Name: <input id="question" class="createQuestionTextBox1" type="text" name="questionName">
Correct Answer: <input id="answer" class="createQuestionTextBox1" type="text" name="correctAnswer">
Option 1: <input id="option1" class="createQuestionTextBox2" type="text" name="option_1">
Option 2: <input id="option2" class="createQuestionTextBox2" type="text" name="option_2">
Option 3 <input id="option3" class="createQuestionTextBox2" type="text" name="option_3">
Option 4 <input id="option4" class="createQuestionTextBox2" type="text" name="option_4">
Option 5 <input id="option5" class="createQuestionTextBox2" type="text" name="option_5">
<input type="Submit" id="questionSubmit" value="Create Question"></input>
</form>
function SubmitFormCreationData() {
$("#questionSubmit").click(function() {
if (CheckCodeField($("#code").val()) == false) {
return false;
} else if (CheckAnswerNameFields($("#question").val()) == false) {
return false;
} else if (CheckCorrectAnswerField($("#answer").val()) == false) {
return false;
} else if (CheckAnswerNameFields($("#option1").val()) == false) {
return false;
} else if (CheckAnswerNameFields($("#option2").val()) == false) {
return false;
} else if (CheckAnswerNameFields($("#option3").val()) == false) {
return false;
} else if (CheckAnswerNameFields($("#option4").val()) == false) {
return false;
} else if (CheckAnswerNameFields($("#option5").val()) == false) {
return false;
} else {
$.post("InsertNewQuestion.php", $('#createQuestionForm').serialize());
alert('Quiz Created');
window.setTimeout(delay,2000);
return true;
}
return false;
});
}
function CheckAnswerNameFields(value) {
var isValid = true;
if (value == "")
isValid = false;
if (value == null)
isValid = false;
for(LCV = 0;LCV <= (count(value)-1); LCV++) {
if(value[LCV] == "'")
isValid = false;
if(value[LCV] == '"')
isValid = false;
}
return isValid;
}
function CheckCodeField(value) {
var isValid = true;
if(isInteger(value) == false)
isValid = false;
if(value < 100000)
isValid = false;
if(value > 999999)
isValid = false;
return isValid;
}
function CheckCorrectAnswerField(value) {
var isValid = true;
if(isInteger(value) == false)
isValid = false;
if(value < 1)
isValid = false;
if(value > 5)
isValid = false;
return isValid;
}
function isInteger(possibleInteger) {
return /^[\d]+$/.text(possibleInteger);
}
Now if the first field is entered correctly then the output is as wanted, false is returned. However if the first field is entered correctly and the rest are blank then the page refreshes, however it should be returning false because I check if the question and option fields are blank. Why is this happening?

$("#questionSubmit").click(function() {
$.post("InsertNewQuestion.php", $('#createQuestionForm').serialize(), function(data){
if(data=='SUCCESS'){
alert('Quiz Created');
window.setTimeout(delay,2000);
return true;
}
else{
var alertx='';
for(i=0;i<data.split('-').length-1;i++) alertx += data.split('-')[i].toString()+"\n";
alert(alertx);
}
});
return false;
});
insertnewquestion.php
extract($_POST);
$errors = '';
if(!in_array($questionCode,range(100000,999999))) $errors .= 'Invalid code-';
if(!in_array($correctAnswer,range(1,5))) $errors .= "Invalid answer-";
for($i=1;$i<=6;$i++){
$var = $i==6 ? $questionName : ${'option_'.$i};
if(empty($var) || strstr($var,'"') || strstr($var,"'")) $errors.= "Invalid ".($i==6?"question name":"option $i")."-";
}
echo $errors=='' ? 'SUCCESS':$errors;
Try and write if work correctly

Related

Laravel 8 - Upload multiple files at the same time with different inputs

I have many input files with different names, but when I upload only one file is saved, that's the reason why?
_form.blade.php :
<input type="file" name="tampak_depan" class="form-control"/>
<input type="file" name="tampak_kiri_depan" class="form-control"/>
<input type="file" name="tampak_kanan_depan" class="form-control"/>
<input type="file" name="tampak_belakang" class="form-control"/>
Controller.php :
tampak depan :
$tampak_depan = $request->file('tampak_depan');
if($tampak_depan !== null) {
$art->tampak_depan = time().'_tampak_depan_'.$tampak_depan->getClientOriginalName();
}
if($tampak_depan !== null) {
$path = 'image/asuransi-kendaraan-bermotor/';
if($tampak_depan->move($path,$art->tampak_depan) == false) {
print $tampak_depan->getErrorMessage();
die;
}
}
tampak kiri depan :
$tampak_kiri_depan = $request->post('tampak_kiri_depan');
if($tampak_kiri_depan !== null) {
$art->tampak_kiri_depan = time().'tampak_kiri_depan'.$tampak_kiri_depan->getClientOriginalName();
}
if($tampak_kiri_depan !== null) {
$path = 'image/asuransi-kendaraan-bermotor/';
if($tampak_kiri_depan->move($path,$art->tampak_kiri_depan) == false) {
print $tampak_kiri_depan->getErrorMessage();
die;
}
}
tampak kanan depan :
$tampak_kanan_depan = $request->post('tampak_kanan_depan');
if($tampak_kanan_depan !== null) {
$art->tampak_kanan_depan = time().'tampak_kanan_depan'.$tampak_kanan_depan->getClientOriginalName();
}
if($tampak_kanan_depan !== null) {
$path = 'image/asuransi-kendaraan-bermotor/';
if($tampak_kanan_depan->move($path,$art->tampak_kanan_depan) == false) {
print $tampak_kanan_depan->getErrorMessage();
die;
}
}
tampak belakang :
$tampak_belakang = $request->post('tampak_belakang');
if($tampak_belakang !== null) {
$art->tampak_belakang = time().'tampak_belakang'.$tampak_belakang->getClientOriginalName();
}
if($tampak_belakang !== null) {
$path = 'image/asuransi-kendaraan-bermotor/';
if($tampak_belakang->move($path,$art->tampak_belakang) == false) {
print $tampak_belakang->getErrorMessage();
die;
}
}
Looks like you're using the right function in the first example, but the wrong function in the others.
In 'tampak depan', you're using $request->file(), but in the others you're using $request->post().
Change those to $request->file() and they should work.

PHP Laravel - If else condition with search filter

The application is built in laravel. I have inserted a new search filter called business status.
this is the output of my page
This is the code on the resource/view/business.blade.php page for Business Status drop down search filter
<form method="get" action="" class="">
<select class="form-control" id="business_status" name="business_status" aria-describedby="business_status">
<option value="" label="Please select">Please select</option>
<option value="1" label="Live" <?php if(isset($_GET["business_status"]) && $_GET["business_status"] == 1){ echo 'selected="selected"';} ?>>Live</option>
<option value="2" label="Sold" <?php if(isset($_GET["business_status"]) && $_GET["business_status"] == 2){ echo 'selected="selected"';} ?>>Sold</option>
----
</select> </form>
#foreach($Businesses as $Business)
<tr>
<td>
---
</td>
<td>--</td>
<td>{{$Business->getStatus()}}</td>
</tr>
This is the code in the backend that is app/businesses.php for the dropdown search
public function scopeSearch($query, $request)
{
if(isset($request->business_status)) {
$query->where('company_status_id', $request->business_status);
}
$query->where('use_conf_box','=',0);
return $query;
}
And this is the code to write the business status in the below table
public function getStatus(){
if(is_null($this->company_status_id)){
return "Awaiting Approval";
} else{
switch ($this->company_status_id) {
case 1:
if($this->isExpired()){
return "Expired";
break;
}
if($this->isExpiring()){
return "Expiring Soon";
break;
}
return "Live";
break;
case 2:
return "Sold";
break;
case 3:
---
default:
return "Awaiting Approval";
}
}
The business whose status is Live they are categorized under few section. such as if a business expiry date is over then it is called expired. If a business expiry date is within 4 weeks then is is called expiring. this options are not inserted in the database. But the conditions are created as follows.
public function isLive(){
if($this->is_approved == 1 && $this->company_status_id != 7 && $this->company_status_id != 6 && $this->company_status_id != 2 && $this->company_status_id != 3 && $this->company_status_id != 8){
return true;
} else {
return false;
}
}
public function isExpired(){
if($this->expiry_date > date("Y-m-d")){
return false;
} else {
return true;
}
}
public function isExpiring(){
if($this->expiry_date > date("Y-m-d", strtotime('+4 weeks'))){
return false;
} else {
return true;
}
}
How to bring those conditions under the filters. Currently all this is falling under live. As you see in the screenshot, if selected live it is also picking the business which is expired.
I want that business to show when some one will select expired.
The easiest way would be to create some scope for each of your test like this :
public function isExpired(){
if($this->expiry_date > date("Y-m-d")){
return false;
} else {
return true;
}
}
public function scopeIsExpired($query){
return $query->where('expiry_date', '>', now());
}
public function isLive(){
if($this->is_approved == 1 && $this->company_status_id != 7 && $this->company_status_id != 6 && $this->company_status_id != 2 && $this->company_status_id != 3 && $this->company_status_id != 8){
return true;
} else {
return false;
}
}
public function scopeIsLive($query){
return $query->notWhereIn('company_status_id', [7, 6, 2, 3, 8])->where('is_approved', 1);
}
then in your controller :
if($request->business_status == 'expired'){
$query->isExpired();
}
if($request->business_status == 'live'){
$query->isLive();
}
and so on...

Adding ajax function in validation

Again, I am working with this form validation. Everything works fine and I like the way it works. Unless I want to add ajax function to check weather username already exist from database. Any body can help? I am not really familiar with ajax and Jquery.
This the php consist of html form, index.php :
<?php
if ($_SERVER["REQUEST_METHOD"] == "POST") {
echo " Form submited....!!!! <br/>";
echo '<br/> Username = '.$_POST['username'];
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js" type="text/javascript"></script>
</head>
<body >
<form method="POST" action="">
<div class="form-group">
<label for="txtUserName" class="col-lg-3 control-label">Username :</label>
<div class="col-lg-9">
<input type="text" id="txtUserName" name="username" placeholder="Create Username" >
<p><small id="elmUserNameError" class="errorMsg"></small></p>
</div>
</div>
<button type="button" onClick="return check_form(this.form);">Submit</button>
</form>
<script>
function check_form(form) {
if(validateForm(form) === true ) {
form.submit();
return true;
}
}
function validateForm(theForm) {
with(theForm) {
return (
isNotEmpty(txtUserName, "Please Create username!", elmUserNameError)
&& isUsernameMinMax(txtUserName, 6,10, "Username must between 6 - 10 characters", elmUserNameError)
&& isUpperCase(txtUserName, "Create Username with UPPERCASE!", elmUserNameError)
&& isMatching(txtUserName, "Username must be UPPERCASE with number and underscore. No white space allowed", elmUserNameError)
// problem here......
&& isUserExis(txtUserName, "Username already exist!", elmUserNameError)
);
return false;
}
return true;
}
function isNotEmpty(inputElm, errMsg, errElm) {
var isValid = (inputElm.value.trim() !== "");
postValidate(isValid, errMsg, errElm, inputElm);
return isValid;
}
function isUsernameMinMax(inputElm, minLength, maxLength, errMsg, errElm) {
var inputValue = inputElm.value.trim();
var isValid = (inputValue.length >= minLength) && (inputValue.length <= maxLength);
postValidate(isValid, errMsg, errElm, inputElm);
return isValid;
}
function isUpperCase(inputElm, errMsg, errElm) {
var isValid = (inputElm.value.trim().match(/^[^a-z]*$/) !== null);
postValidate(isValid, errMsg, errElm, inputElm);
return isValid;
}
function isMatching(inputElm, errMsg, errElm) {
var isValid = (inputElm.value.trim().match(/^\w+$/) !== null);
postValidate(isValid, errMsg, errElm, inputElm);
return isValid;
}
function postValidate(isValid, errMsg, errElm, inputElm) {
if (!isValid) {
// Show errMsg on errElm, if provided.
if (errElm !== undefined && errElm !== null
&& errMsg !== undefined && errMsg !== null) {
errElm.innerHTML = errMsg;
}
// Set focus on Input Element for correcting error, if provided.
if (inputElm !== undefined && inputElm !== null) {
inputElm.classList.add("errorBox"); // Add class for styling
inputElm.focus();
}
} else {
// Clear previous error message on errElm, if provided.
if (errElm !== undefined && errElm !== null) {
errElm.innerHTML = "";
}
if (inputElm !== undefined && inputElm !== null) {
inputElm.classList.remove("errorBox");
}
}
}
</script>
</body>
</html>
I need to add this function but I have no idea how to return ajax call to validate the result. For example here, as I manually write, when user enter 'DADADA', it will return error 'Username already exist!'.
function isUserExis(inputElm, errMsg, errElm){
// maybe ajax call here....
var isValid = (inputElm.value.trim() !== "DADADA");
postValidate(isValid, errMsg, errElm, inputElm);
return isValid;
}
This my php file to be called, check_username.php :
<?php
include('config.php'); // class and configuration
$users = new Users($db);
if($_REQUEST)
{
$username = $_REQUEST['username'];
if ($users->UsernameExist($username) === true) {
echo 'That Username already exist!';
}
}
?>

Passing Special Characters to PHP via AJAX

I'm collecting form data, sending that to PHP validation script through AJAX call. The issue is on special characters the php validation script is not working as expected.
HTML:
<input type="text" name="firstName" class="firstName"
placeholder="[first name]" required autofocus maxlength="25" size="25" />
JS:
$(".button").click(function () {
var firstName = encodeURIComponent($("input.firstName").val());
var datastring = "firstName=" + firstName;
$.ajax({
type: "POST",
url: "/scripts/validateSignup.php",
data: datastring,
cache: false,
success: function (errorMessage) {
//print to screen
}
});
});
PHP Validation
$postData = $_POST;
if (Filter::validateString($postData['firstName']) == false) {
echo "Oops! Some characters used in your first name are not valid.";
}
PHP Filter
//Returns true if string is good, false otherwise
public static function validateString($string) {
$string = trim($string);
if ($string == null || $string == "") {
return false;
} else {
if (preg_match("/[^\.\,\-\_\'\"\#\?\!\:\;\$\#\%\&\+\= a-zA-Z0-9()]/", $string) == true) {
return false;
} else {
return true;
}
}
}
On an empty string it prints error to screen just fine. But if I do something like "~!##$%^&*()", then it accepts the string as good and doesnt throw and error, even though the result of preg_match == false.
$string = trim($string);
if ($string == null || $string == "") {
return false;
} else {
if (preg_match("/[^\.,\-_'\"#?!:;\$#&\+=\sa-zA-Z0-9\(\)]/", $string) == true) {
return false;
} else {
return true;
}
}
That is more valid regex, but not the result you want: you're checking for pretty much all input, so it'll match "abcd" and return false as well. There are 11 characters with special meanings to regular expressions, only those and the " need to be escaped: ^$[]()|.*+-
Try this:-
<?php
$string = "tes$%tname"; // invalid string
//$string = "testname"; // valid string
if(test($string) == false)
{
echo "String is invalid";
}
function test($string){
$string = trim($string);
if ($string == null || $string == "") {
return false;
} else {
if (preg_match("/[^\.,\-_'\"#?!:;\$#&\+=\sa-zA-Z0-9\(\)]/",$string) == true) {
return false;
} else {
return true;
}
}
}
?>
PHPFiddle is here:- http://phpfiddle.org/main/code/cdu-xg2

How can I prevent my form being sent if a user writes misformated entries in my fields? ie. Letters in number fields

What happens:
When I write two values in both text boxes, the page doesn't show the Congratulations message as it should. When I write only 1 value, the correct thing happens, which is not show the congratulations message.
What should happen:
If a user writes only 1 value, the form should still appear with any previously filled out fields still there. If a user writes values in all of the fields, the Congratulations should appear.
Edit - Finally got it working, in case any other newbies want to check it out:
<html>
<head>
<?php
$validForm = false;
function getValue($field){
if(isset($_GET[$field])){
return htmlspecialchars(trim($_GET[$field]));
}
else{
return "";
}
}
function validateForm($value,$type){
$field = $_GET[$value];
//magic goes here.
switch ($type){
case 'required':
if (!isset($field) || ($field=="")){
global $validForm;
$validForm = false;
}
else{
global $validForm;
$validForm = true;
}
break;
case 'email':
$regexp = "/^[_\.0-9a-zA-Z-]+#([0-9a-zA-Z-][0-9a-zA-Z-]+\.)+[a-zA-Z](2,6)$/";
if(isset($field) && preg_match($regexp,$field)){
global $validForm;
$validForm = true;
}
else {
global $validForm;
$validForm = false;
}
break;
case 'number':
if(!isset($field) || ($field=="") || (!is_numeric($field))){
global $validForm;
$validForm = false;
}
else{
global $validForm;
$validForm = true;
}
break;
default:
die('Validacion desconocida.');
}
}
?>
</head>
<body>
<?php validateForm('name','required'); ?>
<?php validateForm('lastname','required'); ?>
<?php if($validForm == false){ ?>
<form action="class2.php" method="get">
<dl>
<dt>First Name:</dt>
<dd><input type="text" value="<?php echo htmlspecialchars(getValue('name')) ?>" name="name" />
</dd>
<dt>Last Name:</dt>
<dd><input type="text" value="<?php echo htmlspecialchars(getValue('lastname')) ?>" name="lastname" />
</dd>
<br />
<dt>
<input type="submit" value="enviar" name="validate"/>
</dt>
</dl>
</form>
<?php
} else {
?>
<h1>Congratulations, you succesfully filled out the form!</h1>
<?php }
?>
</body>
there appears to be a problem with the $validForm variable in the validateForm function.
I think your assuming changes to $validForm inside the function change the same variable name outside the function. because you haven't set it as a global variable it won't do this for you.
You need to look at Variable scope in PHP.
http://php.net/manual/en/language.variables.scope.php
this will explain how you should handle this variable. you can return the value in the function..
e.g for that function just return the variable:
function validateField($value,$type){
//magic goes here.
switch ($type){
case 'required':
if (!isset($value) || ($value== "")){
$valid = false;
}
else{
$valid = true;
}
break;
case 'email':
$regexp = "/^[_\.0-9a-zA-Z-]+#([0-9a-zA-Z-][0-9a-zA-Z-]+\.)+[a-zA-Z](2,6)$/";
if(isset($value) && preg_match($regexp,$variable)){
$valid = true;
}
else {
$valid = false;
}
break;
case 'number':
if(!isset($value) || ($value=="") || (!is_numeric($value))){
$valid = false;
}
else{
$valid = true;
}
break;
default:
die('Validacion desconocida.');
}
return $valid;
}
That will solve the problem in the function
to get the variable out do :
$formValid = true;
if (!validateField($_GET['name'],'required'))
{
$formValid = false;
}
if (!validateField($_GET['lastname'],'required'))
{
$formValid = false;
}
if ($formValid)....
The issue is that you're calling validateForm() after you check the value of $validForm. When you check $validForm right after your body tag, it is always going to be false. It will get set to true (assuming the form is valid) by the time it gets down past the second field, but you're already in the first branch of the if statement at that point, so the "congratulations" message will never be displayed.
To fix, just move your validation calls to before you check the value of $validForm:
<body>
<?php
validateForm($_GET['name'],'required');
validateForm($_GET['lastname'],'required');
if($validForm == false){ ?>
<form>
And so on.
2 things:
1) I don't think your $validForm variable is in scope with the function validateForm. It seems that you would need to call global on it inside the function
global $validate form.
2) you call validateForm after you set it to false. you need to do the checks before you do the conditional.

Categories