how to put multiple grouped && , || conditions using if else - javascript

I want to check conditions with && || groupping it means if one group stisfy then execute the first condition otherwise second and so on so i'll do that with the help of (if else) kindly give me an example
Description:-i have a select box with multiple options so diffrent diffrent div will remain open if the selected option value exists in the session.
<div id="bizseg" class="col-sm-4" <?php if(isset($_SESSION['constitution'])){ if($_SESSION['constitution']=="Individual" && $_SESSION['myprof']=="Self Employed Businessman") {?> style="display:block;" <?php }else { ?> style="display:none;" <?php }} ?> style="display:none;">

Shrbham please read what you posted why 2 if statements???
if it is all tests for true just && them here is the code and formated so it can be read but in HTML output will be 1 line
<div id="bizseg" class="col-sm-4" <?php
if(
isset($_SESSION['constitution']) &&
$_SESSION['constitution'] == $variable &&
$_SESSION['myprof'] == $variable2 ) {
?> style="display:block;" <?php
}else {
?> style="display:none;" <?php } ?>
If's are quite simple true or false
$var1 = "test";
$var2 = "test";
$var3 = "test2";
//so
$result = $var1 == $var2; // true
$result = $var2 == $var3; // false
//(false) (true) // false and anything == false
if($var2 == $var3 && $var1 == $var2); // false
// (false) (true) // true or anything == true
if($var2 == $var3 || $var1 == $var2); // true
if( ($var2 == $var3 || $var1 == $var2) && $var1 == $val3 ) // false
// ((false) || (true)) && (false) ==
// (true) && (false)
//following rules above and false = false;
As "#Lightness Races in Orbit" has said in comments this sort of procedural code is not liked
you can do it as
<?php
if(
isset($_SESSION['constitution']) &&
$_SESSION['constitution'] == $variable &&
$_SESSION['myprof'] == $variable2 )
{
$result = 'style="display:block;"';
}else {
$result = 'style="display:none;"';
}
?>
<div id="bizseg" class="col-sm-4" <?php echo $result ?>

Related

Refreshing owl-carousel2 on dynamic image load

I need to show a carousel of images inside a <td> in a dataTable dynamically, based on a array of images provided by PHP. Right now all I got is a stack of all the images.
Searching online I undestood I have to reload the carousel AFTER all the images in the td are loaded, but I don't know how.
Here's my html:
<?php foreach ($intest as $int) {
if (is_array($int['cartella'])) {
foreach ($int['cartella'] as $cartella){ ?>
<td><div class="owl-carousel owl-theme prova" >
<?php $files = "images/" . Yii::app()->session['dominio']."/".$row['num_registraz']."/". $cartella."/";
//CVarDumper::dump($file);
if(is_dir($files)){
if ($dh = opendir($files)) {
while (false !== ($file = readdir($dh))) {
if($file == '.' || $file == '..'){
continue;
}
$ext = strtolower(pathinfo($file, PATHINFO_EXTENSION));
if ($ext=='jpg' || $ext=='jpeg' || $ext=='png' || $ext=='gif'){?>
<img class="mia" src="<?= $files.$file ?>">
<?php } else if ($ext == 'pdf'){ ?>
<div>File PDF</div>
<?php } else if ($ext == 'doc' || $ext =='docx') {?>
<div>File DOC</div>
<?php } else {?>
<div>Unsupported file</div>
<?php } } } }else if (!is_dir($files)){ ?>
No foto
<?php } } } } } ?>
</div></td>
And here's the Javascript i tried to reload it
var car = $('#prova');
car.on('load', function(){
car.trigger('destroy.owl.carousel');
car.owlCarousel({
'items':1
});
});
Any help would greatly appreciated

How can I change css from php side?

Basically, I want to add an additional class when a certain IF condition is met.
<?php
if($type == 'NEW')
{
$('#'+day+s).addClass('new');
}
if($type == 'USED')
{
$('#'+day+s).addClass('used');
}
?>
You would need to do it through JavaScript / jQuery inside of a PHP conditional.
You can either close your PHP tags while leaving the conditional open:
<?php
if($type == 'NEW')
{
?>
<script>$('#'+day+s).addClass('new');</script>
<?php
}
if($type == 'USED')
{
?>
<script>$('#'+day+s).addClass('used');</script>
<?php
}
?>
Or echo() out the <script> tags from within PHP:
<?php
if($type == 'NEW')
{
echo "<script>$('#'+day+s).addClass('new');</script>";
}
if($type == 'USED')
{
echo "<script>$('#'+day+s).addClass('used');</script>";
}
?>
Having said that, you'd be better off simply altering your logic to output classes based on your conditionals. That way you would simply need to add a regular CSS rule for each class. The right rule would be selected based on which class was outputted.
It should be directly in your HTML :
<div class="<?php if ($type == 'NEW') echo 'new';?>"></div>
You have to assign your calss name in a variable and simply give that to your corresponding MHTL.
<?php
if($type == 'NEW')
{
$style = "class_name for if"; //eg:- new
}
if($type == 'USED')
{
$style = "class_name for else"; //eg:- used
}
?>
//html element
for eg:
<p id="days" class="<?php echo $style;?>"></p>
several ways to do that and depends also in your code
<!-- Assignment inline -->
<div class="<?= $type === 'NEW' ? 'newClass' : 'usedClass'?>"></div>
<!-- Assignment previous -->
<?php
$class = 'defaultClass';
if ($type === 'NEW') { $class = 'newClass'; }
if ($type === 'USED') { $class = 'usedClass'; }
?>
<div class="<?=$class?>"></div>
<!-- Assignment in script -->
<?php $class = $type === 'NEW' ? 'newClass' : 'usedClass'; ?>
<script>
$(document).ready(function(){
$('#'+day+s).addClass('<?= $class ?>');
});
</script>
You can put the if condition of PHP inside class attribute directly. No need to do any method or js for this. You can use the logic as below:
<div class="<?php if($type == 'NEW'){ echo 'new';} else if($type == 'USED'){ echo 'used'; } ?>"></div>

Displaying pop up error message

I have a project where I need to enhance a given website. In the login page i have two fields (Username & password) and would like to display an error message in a pop up window if the user inputs wrong credentials.Was Thinking to do this in javascript The code i have till now is :
if (isset($errors) && !empty($errors)) {
echo '<p id="err_msg">Oops! There was a problem:<br>';
foreach ($errors as $msg) {
echo " - $msg<br>";
}
echo 'Please try again or Register</p>' ;
}
You don't need javascript for this. If you do the validation server side then you can guarantee the content is whats expected. You could use something like the following. Then set a timeout to hide the box if required.
<?php
$sError = '';
$sEmail = '';
// if email posted check/validate
if(isset($_POST['Email']) && $_POST['Email'] != ''){
if(valid_email($_POST['Email'])){
$sEmail = $_POST['Email'];
}else{
$sError .= "[InvalidEmail]";
}
}
// if email is blank after validation, add to error string
if($sEmail == '') $sError .= "[Email]";
// then print using php
if($sError !== ''){
if( strpos($sError, '[Email]') !== false ||
strpos($sError, '[Password]' ) !== false
){
echo"<div class=\"statusMessage alert alert-danger\" role=\"alert\"><ul>";
if(strpos($sError, '[Email]') !== false){
echo "<li>Please enter an email address</li>";
}
if(strpos($sError, '[InvalidEmail]') !== false){
echo "<li>Email provided is invalid</li>";
}
echo "</ul></div>";
}
}
?>

Loop through fields in a form

Assume I have a table. Each row contains form fields that can be populated or not by the user. I need to check that for each row either all the form fields are populated or none.
The html is this:
<tr class="riga_gar">
<td class="report">
<input type="hidden" id="crediti[<?php echo $i; ?>]" name="crediti[<?php echo $i; ?>]"
value="<?php echo $cred['id_cre']; ?>" >
<?php echo $cred['id_cre'] ?>
</td>
<td class="report gbv" data-gbv="<?php echo $cred['gbv_tot']; ?>">
<?php echo num2cur($cred['gbv_tot']); ?>
</td>
<td class="report">
<?php echo veicolo2name($cred['titolare'],$pdo); ?>
</td>
<td class="report">
<?php echo $cred['stato']; ?>
</td>
<td class="report">
<input class="input_field numerico" id="chiesto" type="text" name="garanzia[<?php echo $i; ?>]" value="<?php echo $chiesto; ?>">
</td>
<td class="report">
<select name="tipo_gar[<?php echo $i; ?>]">
<option value="">Scegli</option>
<?php foreach($tipo_gars as $tipo_gar){
echo '<option value="'.$tipo_gar['id'].'">'.$tipo_gar['descrizione'].'</option>';
}?>
</select>
</td>
</tr>
What I am trying to do is to check that for each row both the input and the select have a value or none.
I started with this js:
function ajax_submit(){
var submit_val=$("#garante").serialize();
dest="anagrafiche/new_garante1.php";
$('.riga_gar').each(function(i,obj){
if ($(this).val()!='') {
}
});
}
and I want to run this ajax function:
$.ajax({
type: "POST",
url: dest,
data: submit_val,
success: function(data){
data1=data.split("|");
if(data1[0]=="Successo"){
$("#spnmsg").fadeTo(200,0.1,
function(){$(this).removeClass().addClass("spn_success").html(data1[1]).fadeTo(900,1)});
}else if(data1[0]=="Errore"){
$("#spnmsg").fadeTo(200,0.1,
function(){$(this).removeClass().addClass("spn_error").html(data1[1]).fadeTo(900,1)});
}
},
complete: function(){
$.fancybox.close();
//setTimeout(function(){ $('.container').load('sofferenze/dashboard.php?from=<?php echo $id_soff ?>');},3000);
setTimeout(function(){
$('#upper').load('sofferenze/soff.php?soff=<?php echo $id_soff ?>');
$("#spnmsg").fadeTo(200,0.1,
function(){$(this).removeClass().addClass("spn_normal").html('Cruscotto della sofferenza <?php echo soff2name($id_soff,$pdo); ?>').fadeTo(900,1)});
},3000);
} //chiudo complete function
}); //chiudo $.ajax
only when:
at least one row have both values;
all the rows that have values have both of them;
but I get stuck at how to refer to the value of input and select in the each loop so that I can check my conditions.
I think this will help you. This will read each row and ignore your hidden field. Once code will find both values populated than validateForm variable will be true and will become false if in next row one value from both input or select will be empty.
$(document).ready(function(){
var validateForm = false;
var check = 0;
$("form").on('submit',function(){
$("tr").each(function(){
console.log($.trim($(this).find("input.input_field").val()) +", "+ $.trim($(this).find("select").val()));
if($.trim($(this).find("input.input_field").val()) != "" && $.trim($(this).find("select").val()) != ""){
validateForm = true;
}
else{
if($.trim($(this).find("input.input_field").val()) == "" && $.trim($(this).find("select").val()) != ""){
if(validateForm){
validateForm = false;
check = 1;
return false;
}
}
if($.trim($(this).find("input.input_field").val()) != "" && $.trim($(this).find("select").val()) == ""){
if(validateForm){
validateForm = false;
check = 1;
return false;
}
}
}
});
if(validateForm && check == 0){
validateForm = true;
}
else{
validateForm = false;
}
if(validateForm){
//call ajax
}
});
});
Demo:https://jsfiddle.net/87tkraas/
This is untested but how about something like this:
var allowSubmit = false;
$("form").on("submit", function(e) {
$("tr").each(function() {
var input = $(this).find("input").val();
var select= $(this).find("select").val();
if ((input == "" && select != "") || (input != "" && select == "")) {
return;
} else if (input != "" && select != "") {
allowSubmit = true;
}
});
if (allowSubmit == false) {
e.preventDefault();
}
});

JavaScript and PHP sessions

My login.php looks like:
if ($count == 1){
$_SESSION['username'] = "1";
if (isset($_SESSION['username'])){
ob_start();
$url = 'main.php';
while (ob_get_status())
{
ob_end_clean();
}
header( "Location: $url" );
}
}
else {
$_SESSION['username']='';
}
and when I succesfully log in, main.php redirects me to login.php instead of running the game loop.
<?php
if(!(isset($_SESSION['username']) && $_SESSION['username']!='')) {
echo "<script>window.location.href=\"login.php\"</script>";
}
else {
echo "<script defer>reload();</script>";
}
?>
Thank you.
try instead
<?php
session_start();
if(empty($_SESSION['username'])) {
echo "<script>window.location.href=\"login.php\"</script>";
}
else {
echo "<script defer>reload();</script>";
}
Emptychecks
"" (an empty string)
0 (0 as an integer)
0.0 (0 as a float)
"0" (0 as a string)
NULL
FALSE
array() (an empty array)
$var; (a variable declared, but without a value)
or do $_SESSION['username']=='' check.
I think your main php code should change like this..
<?php
if(!(isset($_SESSION['username']) && $_SESSION['username']=='')) {
echo "<script>window.location.href=\"login.php\"</script>";
}
else {
echo "<script defer>reload();</script>";
}
?>
here you are checking $_SESSION['username']!=''
Need to change that to..
if(!(isset($_SESSION['username']) && $_SESSION['username']==''))

Categories