detect empty field - problem - php

I am trying detect in ajax what is the field that is empty. (echo $field; >>> output is radios)
This if (!data.livre && data.livre == "radios") { checks if data.livre is not true (that is working) and now i want to check if the echo is radios or not. If is radios i showed to the user: empty radios
function check($form) {
$fields = array("radios", "age");
foreach($fields as $field) {
if(empty($form[$field])) {
echo $field;
return false;
}
}
return true;
}
$data = array();
$data['livre'] = $val-> check($form);
echo json_encode($data);
JSON output:
radios{"livre":false}
js
success: function(data) {
if (!data.livre && data.livre == "radios") { //problem here
$("#msgbox1").fadeTo(200, 0.1, function() {
$(this).html('empty radios').addClass('messageboxerror1').fadeTo(900, 1);
});
}
}
EDIT: What is the best way to identify if the field that is empty is radios or age ?
thanks

If the result can be that only radios or age or none of both can be empty then you have to edit your check to !data.livres || data.livres == "radios" || data.livres == "age". It will then print the message if your json output is the following:
{livres: false}
or
{livres: "radios"}
or
{livres: "age"}
Edit: Changes according to your comment
if (!data.livre) { //problem here
// Do whatever you want to do when livres is false
} else if (data.livre == "radios") {
// Do whatever you want to do when livres is "radios"
} else if (data.livre == "age") {
// Do whatever you want to do when livres is "age"
}

Related

Fill array regardless if there is empty check

So I have the following code:
if ($obj->updated_date > $record->updated_date || $mode === 'refresh') {
if (empty($obj->birthday) || $obj->hire_date) {
$record->fill([
'birthday' => '',
'hire_date' => ''
]);
} else {
$record->fill($arr);
}
} else {
$record->timestamps = false;
}
Where I'm checking if $obj->birthday or $obj->hire_date is empty, and then define them as empty strings, but here is the problem.
I want to be able to call $record->fill($arr) regardless and prepopulate all my fields on the empty check, but for some reason I can't seem to figure out out.
So heres the logic:
Empty hire_date? set as ''.
Empty birthday? set as ''.
Populate the rest of the fields..
Both hire_date and birthday not empty? Populate all fields.
You can try this:
if ($obj->updated_date > $record->updated_date || $mode === 'refresh') {
$filllArray = $arr;
if (empty($obj->birthday) {
$record->fill([
'birthday' => ''
]);
unset($filllArray['birthday']);
}
if (empty($obj->hire_date)) {
$record->fill([
'hire_date' => ''
]);
unset($filllArray['hire_date']);
}
$record->fill($filllArray);
} else {
$record->timestamps = false;
}
Update 1: Copy the $arr to $filllArray and update the new array to determine what should be filled or not.
I know you've accepted an answer. This is a slightly different way of achieving the same thing (If I understood the question correctly)
if ($obj->updated_date > $record->updated_date || $mode === 'refresh') {
$fa = [];
empty($obj->birthday) ? $fa['birthday'] = '' : $fa['birthday'] = $obj->birthday;
empty($obj->hire_date) ? $fa['hire_date'] = '' : $fa['hire_date'] = $obj->hire_date;
$merged_arr = array_merge($arr, $fa);
$record->fill($merged_arr);
} else {
$record->timestamps = false;
}

How to set limitations for checkbox using ajax and session?

I have never done combining ajax and session before. So far i have done something like this.
var sessionvar;
$.ajaxSetup({cache: false})
$.get('test.php' ,function (data) {
sessionvar = data;
alert(sessionvar);
var checkedCbs = $('sessionvar:checked');
if (checkedCbs.length === 4) {
alert("You can only select 3 books");
this.checked = false;
}
});
I want to try set the limitations based on session. Inside the test.php i have something like this
<?php
session_start();
if(isset($_POST['sBorrow']) && $_POST['action']){
if(isset($_SESSION['sBorrow']) && is_array($_SESSION['sBorrow'])){
$sborrow = $_POST['sBorrow'];
$set = $_SESSION['sBorrow'];
}
else{
$set = array();
}
if($_POST['action'] == "SET"){
array_push($set, $_POST['sBorrow']);
$_SESSION['sBorrow'] = $set;
}
else if($_POST['action'] == "UNSET"){
$unset = $_SESSION['sBorrow'];
if(($key = array_search($_POST['sBorrow'], $unset)) !== false) {
unset($unset[$key]);
$_SESSION['sBorrow'] = $unset;
}
}
}
//session_destroy();
if(isset($_SESSION['sBorrow'])){
$countses = count($_SESSION['sBorrow']);
echo $countses;
}
// nothing requested, so return all values
print json_encode($_SESSION);
?>
Inside these i have create some array to store something. Never mind that, i just want to know how to run an ajax with session. Im not sure if my codes is right for implementing that.

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

Nesting if else statements in PHP to validate a URL

I'm currently writing up a function in order to validate a URL by exploding it into different parts and matching those parts with strings I've defined. This is the function I'm using so far:
function validTnet($tnet_url) {
$tnet_2 = "defined2";
$tnet_3 = "defined3";
$tnet_5 = "defined5";
$tnet_7 = "";
if($exp_url[2] == $tnet_2) {
#show true, proceed to next validation
if($exp_url[3] == $tnet_3) {
#true, and next
if($exp_url[5] == $tnet_5) {
#true, and last
if($exp_url[7] == $tnet_7) {
#true, valid
}
}
}
} else {
echo "failed on tnet_2";
}
}
For some reason I'm unable to think of the way to code (or search for the proper term) of how to break out of the if statements that are nested.
What I would like to do check each part of the URL, starting with $tnet_2, and if it fails one of the checks ($tnet_2, $tnet_3, $tnet_5 or $tnet_7), output that it fails, and break out of the if statement. Is there an easy way to accomplish this using some of the code I have already?
Combine all the if conditions
if(
$exp_url[2] == $tnet_2 &&
$exp_url[3] == $tnet_3 &&
$exp_url[5] == $tnet_5 &&
$exp_url[7] == $tnet_7
) {
//true, valid
} else {
echo "failed on tnet_2";
}
$is_valid = true;
foreach (array(2, 3, 5, 7) as $i) {
if ($exp_url[$i] !== ${'tnet_'.$i}) {
$is_valid = false;
break;
}
}
You could do $tnet[$i] if you define those values in an array:
$tnet = array(
2 => "defined2",
3 => "defined3",
5 => "defined5",
7 => ""
);

Append json messages when multiple json arrays are echo'd with jQuery

I have 2 classes that return a json encoded array if an error message is added to the $_error array:
Validate.class.php:
public function showResponse()
{
if(!empty($this->_error)) {
return json_encode($this->_error);
}
else {
return true;
}
}
UserTools.class.php:
public function showResponse()
{
if(!empty($this->_error)) {
return json_encode($this->_error);
}
else {
return true;
}
}
Then in ajax.php I check if either of those classes return true, if so a new user can be added by a User class, then the user class will return a success response, if they don't return true, the json encoded errors in either UserTools.class.php or Validate.class.php are returned by either of those classes:
ajax.php
if($validate->showResponse() === true && $user_tools->showResponse() === true) {
$user = new User($username, $password, $email);
$user->save();
echo $user->showResponse();
}
else {
echo $user_tools->showResponse();
echo $validate->showResponse();
}
Firebug shows that everything get's returned as expected, UserTools.class.php returns the usernameexists error and Validate.class.php returns the others:
{"error":{"usernameexists":"Username already taken"}}
{"error":{"password":"This field is required","password_again":"This field is required","email":"This field is required"}}
Yet I can't display either of those messages via jQuery, if I remove 'echo $user_tools->showResponse();' from 'else' in ajax.php, the error messages do get appended correctly, when I want to display both errors, nothing get's appended.
jQuery file:
if(msg.error) {
if(msg.error['usernameexists']) {
$('#msg-username').show().html('<p></p>').addClass('error');
$('#msg-username p').append(msg.error['username']);
}
if(msg.error['username']) {
$('#msg-username').show().html('<p></p>').addClass('error');
$('#msg-username p').append(msg.error['username']);
}
if(msg.error['password']) {
$('#msg-password').show().html('<p></p>').addClass('error');
$('#msg-password p').append(msg.error['password']);
}
if(msg.error['password_again']) {
$('#msg-password_again').show().html('<p></p>').addClass('error');
$('#msg-password_again p').append(msg.error['password_again']);
}
if(msg.error['email']) {
$('#msg-email').show().html('<p></p>').addClass('error');
$('#msg-email p').append(msg.error['email']);
}
}
The reason its not working is because there are 2 seperate json objects
One way is to combine them, for that put this in your ajax.php
if($validate->showResponse() === true && $user_tools->showResponse() === true) {
$user = new User($username, $password, $email);
$user->save();
echo $user->showResponse();
}else {
$r1 = $user_tools->showResponse();
$r2 = $validate->showResponse();
if($r1 !== true && $r2 !== true){
$r1 = json_decode($r1);
$r2 = json_decode($r2);
foreach($r2['error'] as $k => $v)
$r1['error'][$k] = $v;
$r1 = json_encode($r1);
}else if($r1 === true){
$r1 = $r2;
}
echo $r1;
}
Other easier way would be to return the error object itself instead of json_encoded one from Validate.class.php and UserTools.class.php and combine them in ajax.php then output the json_encoded string. this would save the 2 json_decode calls in the above code.
Your return string contains two objects and i think that is what (rightly) confuses the json parser. Try prepending a { and appending a } to the else output, and separate the two objects with a comma

Categories