Bootstrap - How to save the state of collapse in a SESSION - php

I use Bootstrap and I would like to save the current state of collapse (open or close) in a session variables PHP (not in a cookie).
Could you give me :
- an example code to save the current state in a session variable PHP.
- and an example code to open or not the collapse (depends on the state stored in the session variable) when the page loads.
Thank you very much

First of all, do you really need to store it into session? Does some PHP script work with that value?
Both cases:
You must store somewhere in JavaScript variable the state of collapsed items:
var collapsed = false; // the default value
$('.collapse').on('hide.bs.collapse', function () {
collapsed = true; // on hide, collapsed is true
})
$('.collapse').on('show.bs.collapse', function () {
collapsed = false; // on show, collapsed is false
})
Yes, i need to store it into session:
At each request, you must add the collapsed variable and pass it for example trhough GET method:
$('a').on('mousedown', function() {
var c = collapsed ? 1 : 0;
var href = $(this).attr('href');
if(href.indexOf('?') !== -1) {
$(this).attr('href', href + '&collapsed=' + c);
else {
$(this).attr('href', href + '?collapsed=' + c);
}
});
And somehow save it to session
$_SESSION['collapsed'] = $_GET['collapsed'];
No, i don't need to store into session:
Most modern browsers now have localStorage variable, which is something like session in JavaScript.
Save into variable (in event handlers for example):
if(typeof(Storage)!=="undefined")
{
window.localStorage.setItem('collapsed', collapsed); // saves with no expiration
code.sessionStorage.setItem('collapsed', collapsed); // saves until browser is closed
}
else
{
// Sorry! No Storage support..
}
Load in some startup script:
if(typeof(Storage)!=="undefined")
{
collapsed = window.localStorage.getItem('collapsed'); // again choose one
collapsed = code.sessionStorage.getItem('collapsed');
if(collapsed) {
$('.collapse').collapse('show');
} else {
$('.collapse').collapse('hide');
}
}
else
{
// Sorry! No Storage support..
}
There may be other solutions, but these are the only i can think about. :)
All codes require jQuery

I would do something like this on the PHP side of things. It allows for storing and retrieving the state of multiple ID:s. Session handling is not included; the functions assume there is an active session going. Also, the functions are static since there is no real need to instantiate a class. And it makes for simpler usage.
class Collapse
{
public static function set_state($id = null, $state = null)
{
if ($id === null || $state === null || !is_numeric($state)) {
return false;
} else {
$state = ($state == 0 ? 0 : 1);
$_SESSION['collapse_state'][$id] = $state;
}
}
public static function state($id = null)
{
if ($id === null) {
return false;
} else {
return $_SESSION['collapse_state'][$id];
}
}
}
// --- Sets the state for chosen ID.
Collapse::set_state('info', 0);
// --- Returns the state of the ID.
Collapse::state('info');
Use this class together with the JavaScript proposed by Tomáš Tomíík Blatný and you'll be able to save your states. I'd probably use POST instead of GET though, to make the URL:s look a bit nicer. This can be done by populating a hidden form field or by sending an AJAX request to a PHP-script that only handles the collapse states.

Related

how to display JSON output fetched from the oracle database with line breaks

I have an HTML page which is has one user input and one button. After clicking on the button, we can fetch other data related to that user from oracle database. i have defined my code in a seperate php page( index2.php ) which looks like below:-
<?php
class logAgent
{
const CONFIG_FILENAME = "data_config.ini";
private $_dbConn;
private $_config;
function __construct()
{
$this->_loadConfig();
$this->_dbConn = oci_connect($this->_config['db_usrnm'],
$this->_config['db_pwd'],
$this->_config['hostnm_sid']);
}
private function _loadConfig()
{
// Loads config
$path = dirname(__FILE__) . '/' . self::CONFIG_FILENAME;
$this->_config = parse_ini_file($path) ;
}
public function fetchLogs() {
$userid =$_POST["userid"];
$sql = "SELECT REQUEST_TIME,WORKFLOW_NAME,EVENT_MESSAGE
FROM AUTH_LOGS WHERE USERID = '".$userid."'";
//Preparing an Oracle statement for execution
$statement = oci_parse($this->_dbConn, $sql);
//Executing statement
oci_execute($statement);
$json_array = array();
while (($row = oci_fetch_row($statement)) != false) {
$rows[] = $row;
$json_array[] = $row;
}
echo json_encode($json_array);
}
}
$logAgent = new logAgent();
$logAgent->fetchLogs();
?>
I am doing this using asynchronous post method my defining a javascript file(script.js)
$(document).ready(function(){
$("#mybtn").click(function(e){
e.preventDefault();
var userid = $("#userid").val();
//$.post("index2.php", {"userid" : userid})
var posting = $.post( 'index2.php', {"userid" : userid});
posting.done(function( res ) {
var response = $.parseJSON(res);
$('#rawResponse').text(response);
});
});
})
I have many data for one user. And output display looks like:
03-SEP-18,softOtpCheck,OTP check passed,03-SEP-18,createAuthenticatedSession,yoya session Created.,03-SEP-18,createAuthenticatedSession,yoya session Created.,03-SEP-18,oamAuth,OAM context cookie collected.,03-SEP-18,softOtpCheck,OTP check passed,03-SEP-18,createAuthenticatedSession,yoya session Created.,03-SEP-18,createAuthenticatedSession,yoya session Created.,03-SEP-18,oamAuth,OAM context cookie collected.
But i want it as :
03-SEP-18,softOtpCheck,OTP check passed,
03-SEP-18,createAuthenticatedSession,yoya session Created.,
03-SEP-18,createAuthenticatedSession,yoya session Created.,
03-SEP-18,oamAuth,OAM context cookie collected.,
03-SEP-18,softOtpCheck,OTP check passed,
03-SEP-18,createAuthenticatedSession,yoya session Created.,
03-SEP-18,createAuthenticatedSession,yoya session Created.,
03-SEP-18,oamAuth,OAM context cookie collected.
How can i display my output in a newline?
I believe you want to change
$('#rawResponse').text(response);
to
$('#rawResponse').html('<pre>' + JSON.stringify(response, null, 2) + '</pre>);
See JSON.stringify and the enclosing pre tags will display the return value nicely.
Alternatively you could also put it into a textarea, it will also display the newlines properly.
If you want to echo the json data, you can returns prettified data with newline characters using JSON_PRETTY_PRINT
echo json_encode($json_array, JSON_PRETTY_PRINT);

Issue with redirect() when using conditional to evaluate multiple form buttons

So I've built a small conditional to evaluate which button is pressed in my form (as there are 2). This works fine and fires off the correct method and writes the appropriate data to the DB, however my redirect is not working. It saves() to the DB and then simply stays on the page designated as the POST route.
I suspect the problem has something to do with my conditional and the use of $this.
Here is my check_submit method:
public function check_submit()
{
if(!is_null(Input::get('add_to_invoice'))){
$this->invoice_add_item();
} elseif(!is_null(Input::get('complete_invoice'))) {
$this->invoice_complete();
}
}
Here is one of the 2 methods which I am currently testing:
public function invoice_add_item()
{
$input = Request::all();
$invoice_items = new Expense;
$invoice_items->item_id = $input['item_id'];
$invoice_items->category_id = $input['category'];
$invoice_items->price = $input['price'];
$invoice_items->store_id = $input['store'];
if(Input::has('business_expense'))
{
$invoice_items->business_expense = 1;
}
else{
$invoice_items->business_expense = 0;
}
$invoice_items->save();
return redirect('/');
}
Perhaps there is a better way of handling this in my routes(web) file, but I'm not sure how to go about this.
You should add the return to the check_submit() method. Something like
public function check_submit()
{
if(!is_null(Input::get('add_to_invoice'))){
return $this->invoice_add_item();
} elseif(!is_null(Input::get('complete_invoice'))) {
return $this->invoice_complete();
}
}
Better yet, you should probably return a boolean on invoice_add_item() and based on that, redirect the user to the correct place (or with some session flash variable with an error message)

ngIf doesn't update with variable

I have a very simple ng-if construction using two MD buttons and one AngularJS scope variable isPlaying. However, the ng-if doesn't seem to work along with the variable. I can see the variable changing as I click the buttons, using console tools, however no changes to the DOM. Strangely enough the ng-if does seem to trigger when I hover other Angular components, such as buttons in the main nav.
HTML/MD/PHP:
<md-button class="md-icon-button" ng-if="!isPlaying" ng-click="play()" aria-label="Play">
<md-icon md-svg-src="<?php echo get_stylesheet_directory_uri(); ?>/img/icon/ic_play_arrow_black_24px.svg"></md-icon>
</md-button>
<md-button class="md-icon-button" ng-if="isPlaying" ng-click="pause()" aria-label="Pause">
<md-icon md-svg-src="<?php echo get_stylesheet_directory_uri(); ?>/img/icon/ic_pause_black_24px.svg"></md-icon>
</md-button>
JS:
$scope.play = function () {
player.playVideo();
$scope.isPlaying = true;
}
$scope.pause = function () {
player.pauseVideo();
$scope.isPlaying = false;
}
The problem was being caused by a function wrapped inside a timeout block. I replaced the setTimeout with $timeout and everything started working fine:
$scope.isPlaying = false;
$scope.videoTime = 0;
function onPlayerStateChange() {
console.log(player);
if (player.getPlayerState() === 1)
$scope.isPlaying = true;
else
$scope.isPlaying = false;
$timeout(onPlayerStateChange, 500);
}

PHP dynamic link list breaks ajax

I have this list of things generated from an array, where the array value maps to the array key, which maps to a query in the database. Now the problem I'm facing is that when this list is included in my ajax portion, it only works for one click before the page refreshes. What gives?
I'm using the HTML5 History API method to change the url upon clicks by the href="" portion of the link.
I'm somewhat new to jQuery, which is odd since I'm a front end developer primarily but I just never got the time to catch up, but my link list breaking this code just doesn't make sense to me.
$("a[rel='ajax']").click(function(e){
//e.preventDefault();
pageurl = $(this).attr('href');
$.ajax({url:pageurl+'?rel=ajax',success: function(data){
$('#ajax')
.load(pageurl + ' #resultati');
}});
if(pageurl!=window.location){
window.history.pushState({path:pageurl},'',pageurl);
}
return false;
});
The links are generated using this function in PHP, I'm using the laravel framework if that makes any difference.
public static function filterlink ($filter, $what)
{
if (URI::segment(2) == 'make')
{
$first = URI::segment(3);
$next = URI::segment(4);
}
else
{
$first = URI::segment(2);
$next = URI::segment(3);
}
// what == 0 is the filter, what == 1 is the +filter. This reffers to the link being created.
switch (substr($first, 0, 1))
{
case ' ': // example.ex/make/[+]current starts with a plus sign.
if($what == 0)
//new no+ filter.
{
return HTML::link('make/'.self::slug($filter.'/'.$first), $filter, array('rel' => 'ajax'));
// example.ex/make/+current => example.ex/make/newfilter/+current
}
elseif($what == 1)
//new +filter
{
return HTML::link('make/+'.self::slug($filter), $filter, array('rel' => 'ajax'));
// example.ex/make/+current+replaced+by+newfilter
}
break;
default:
if($what == 0)
// new no+ filter.
{
if(!empty($next))
{
return HTML::link('make/'.self::slug($filter.'/'.$next), $filter, array('rel' => 'ajax'));
}
else
{
return HTML::link('make/'.self::slug($filter), $filter, array('rel' => 'ajax'));
}
}
elseif($what == 1 && (!empty($first)))
{
return HTML::link('make/'.self::slug($first.'/+'.$filter), $filter, array('rel' => 'ajax'));
}
elseif($what == 1 && (empty($first)))
{
return HTML::link('make/+'.self::slug($filter), $filter, array('rel' => 'ajax'));
}
}
}
I've tried putting my link lists outside the ajax field, which keeps the ajax flow going without any boring page refreshes, but my link urls don't update, obviously, and I'm only able to construct one-ended links, breaking the pages dual filter functionality.
Any help would be great.
If you're actually loading HTML content with links that you want to be AJAX friendly, then you'll need to use .on so that the new links also get taken over by your jQuery function.
$(document).on('click',"a[rel='ajax']",function(e) {
Working sample here:
http://jsfiddle.net/hansvedo/cJW54/
Just a quick thought, what about placing preventDefault where the pushState function is? Or even just uncommenting it where it is? preventDefault prevents the normal linking action from happening.
if(pageurl!=window.location){
e.preventDefault();
window.history.pushState({path:pageurl},'',pageurl);
}

Update Class variable outside PHP Class

I'm gonna make this too complicated, just going to break it down to the main parts.
I have a form that changes the boolean of a variable when the form gets submitted, however it gets called by a function, the function has to change the variable.
class updates
{
var $yesno = false;
function updateBool()
{
$this->yesno = true;
}
}
So when the form gets submitted, it will call $up->updateBool() to change the boolean to true. When I do var_dump($up->yesno), it says false when it should be true. If I do this:
class updates
{
var $yesno = false;
function updateBool()
{
$this->yesno = true;
var_dump($this->yesno); // <-- outputs true
}
}
So how come I cannot get the variable to print out true in a seperate script?
EDIT:
$sql = "SELECT boolean
FROM config
WHERE boolean = 'true'";
$result = mysql_query($sql);
if(mysql_num_rows($result) > 0)
{
$up->updateBool();
}
else
{
header("Location: index.php?d=none");
}
This is part of the code where it gets called. I can confirm there are more than 1 record in the SQL statement.
So when the form gets submitted, it will call $up->updateBool() to change the boolean to true
You seem to be switching to a new page, where $up will be a new object. Objects do not persist across requests. PHP "loses its memory" when you call a new page, and all variables are started from scratch.
To persist values across page requests, you would need to use something like sessions.
class updates
{
public $yesno;
function __construct(){
$this->yesno = false;
}
function updateBool()
{
$this->yesno = true;
}
}

Categories