how to stay on the last view after reloading the page (fullcalendar) - laravel-5

I use fullcalendar in laravel 5.6.
My default view is the month view, and I want to stay on the last view after reloading the page.
example: if I switch to the week view, I want to be able to stay on this view week after refreshing the page and not return to the month view.
Thank you for helping me if you have a solution.

For V5:
var iv = localStorage.getItem("fcDefaultView") || 'timeGridWeek'
var id = localStorage.getItem("fcDefaultDate") || new Date
var calendar = new FullCalendar.Calendar(calendarEl, {
initialView: iv,
initialDate: id,
datesSet: function (dateInfo) {
localStorage.setItem("fcDefaultView", dateInfo.view.type);
localStorage.setItem("fcDefaultDate", dateInfo.startStr);
},
})
calendar.render()

It is really simple, just add the following lines to your .fullCalendar initialization:
viewRender: function (view, element) {
// when the view changes, we update our localStorage value with the new view name
localStorage.setItem("fcDefaultView", view.name);
},
defaultView: (localStorage.getItem("fcDefaultView") !== null ? localStorage.getItem("fcDefaultView") : "month"),
Rgds. Senad

use jquery cookie library to store current view using the viewRender event and then use the follwing method to switch to it,
$('#calendar').fullCalendar( 'changeView', 'basicDay' );
here is the reference for viewRender event which is triggered while you switch among views.
https://fullcalendar.io/docs/viewRender

For V4:
viewSkeletonRender: function (view, element) {
// when the view changes, we update our localStorage value with the new view name
localStorage.setItem("fcDefaultView", view.view.type);
},
defaultView: (localStorage.getItem("fcDefaultView") !== null ? localStorage.getItem("fcDefaultView") : "month"),

I had problems with localStorage. For me it only works with localhost, but not on a remote server.
Instead I use ajax and php to store the variable in $_SESSION. Note that the startStr variable returns the first box date, which is the previous month if the first day of the month is not a Sunday. This is corrected for in the php code, by adding 7 days.
Remember to include a session_start(); at the top of your main file.
PHP & Javascript in main file:
var calendarEl = document.getElementById('calendar');
<?php
if(isset($_SESSION['startdate'])) echo "var id = '".$_SESSION['startdate']."';";
else echo "var id = new Date;"
?>
var calendar = new FullCalendar.Calendar(calendarEl, {
initialDate: id,
datesSet: function (dateInfo) {
$.post("./setdate.php", {startdate : dateInfo.startStr}); // posts current view date for storage in $_SESSION
},
.....
PHP code (setdate.php):
<?php
session_start();
$date = strtotime(substr($_POST['startdate'], 0, 10));
$date = strtotime("+7 day", $date); // the datestring relates to the first box, which is usually the previous month, so add a week to get to correct month
$_SESSION['startdate'] = date("Y-m-d", $date);
?>
My example only stores the month, not the view, but the code can easily be extended to include that.

Related

How can I use WordPress ajax to set a cookie and redirect before a page loads

I’m working on a WordPress site requirement to redirect a user when they’re in a certain country to their country specific homepage.
(I’ve had to do this via WP Ajax because full page caching prevents it working directly on live hosting environment - I was previously doing it quite simply in functions.php hooked into 'init').
This works when I call it at the start of the header template, but only after the current page content is shown. It would be great if I could hook it in to happen before the page is displayed e.g. like using hooks such as: 'wp_loaded', ‘template_redirect’ but jQuery needs to be available...
Here is my code. It needs tidying some more but appreciate any suggestions as how to make a redirect happen before page contents displayed?
function invoke_county_redirection() {
ob_start();
?>
<script type="text/javascript">
var ajax_url = "<?= admin_url( 'admin-ajax.php' ); ?>";
jQuery.post(ajax_url, {
'action': 'country_redirection',
}, function (response) {
// Set the cookie to say we're performing the redirect - this will flag it not to happen again
createCookie('redirected', 'true');
if (response != '') {
window.location.replace(response);
}
function createCookie(name, value, days) {
var expires = "";
if (days) {
var date = new Date();
date.setTime(date.getTime() + (days * 24 * 60 * 60 * 1000));
expires = "; expires=" + date.toUTCString();
}
document.cookie = name + "=" + value + expires + "; path=/";
}
</script>
<?php
echo ob_get_clean();
return;
}
function country_redirection() {
$redirect_url = '';
if ( $_COOKIE['redirected'] !== 'true' ) {
/* declare empty result url */
$result['url'] = '';
/* Call on geoip plugin to get the country from their IP address */
$userInfo = geoip_detect2_get_info_from_current_ip();
$country_code = $userInfo->country->isoCode;
/* if we've retreived the country code for the current user */
if ( $country_code ) {
/* GET THE CORRECT REDIRECT URL IF APPLICABLE TO THE USER COUNTRY */
$redirect_url = get_country_url($country_code);
}
}
echo $redirect_url;
wp_die();
}
add_action( 'wp_ajax_nopriv_country_redirection', 'country_redirection' );
add_action( 'wp_ajax_country_redirection', 'country_redirection' );
Quick update in case anyone else can be helped by this.
I hooked the hooked the function invoke_county_redirection() into the wp_head hook as follows...
add_action('wp_head', "invoke_county_redirection");
This means that jQuery would be loaded and the country detect/redirect process runs.
However, it doesn't make the request syncronous and in this particular scenario with wanting to redirect before the page loads, I have given up on this. There is a minefield of issues trying to get around full page caching trying to store a cookie and do a redirect before the page loads. I should have just insisted that caching remained off where this needs to run, so this is our conclusion. We are instead optimsing the site as best we can with GTMetrix and loader.io and we will cross the bridge of scalability as and when we need to.

How to using jtable plugin in codeigniter?

I'm trying to use jtable plugin in framework codeigniter but i got a problem. I'm confused how to pass variable from view (jtable javascript code) to controller and to pass json_encode from controller to view.
Here are my code.
in my view page(Attendance_view.php).
[html code]
<input style="width:100px" type="text" id="from" name="from" value="<?php echo date("Y-m")."-01";?>">
[js code]
//Prepare jTable
var base_url ="<?=base_url()?>";
$('#TableContainer').jtable({
title: 'Attendance',
paging: true,
sorting: true,
defaultSorting: 'month ASC',
selecting: true, //Enable selecting
multiselect: true, //Allow multiple selecting
selectingCheckboxes: true, //Show checkboxes on first column
actions: {
listAction: '<?=base_url()?>index.php/Attendance_controller/listRecord',
createAction: '<?=base_url()?>index.php/Attendance_controller/create',
updateAction: '<?=base_url()?>index.php/Attendance_controller/update',
deleteAction: '<?=base_url()?>index.php/AttendanceAbsensi_controller/delete'
},
....//another field here
});
//Load attendance from server
$('#TableContainer').jtable('load',{
month:$("#from").val()
});
in my controller(Attendance_controller.php)
function listRecord()
{
$this->load->model('Attendance_action');
$jTableResult=$this->Attendance_action->list_record();
$data['jTableResult']= json_encode($jTableResult);
$this->load->view('Attendance_view',$data['jTableResult']);
}
in my model (Attendance_action.php)
function list_record()
{
//get post variable
$date=$this->input->post('month'); // i can't get the value.
//Get record count
$result = //my query here[select "some data" from "mytable" where month='$date']
$recordCount = mysql_num_rows($result);
//Add all records to an array
$rows = array();
while($row = mysql_fetch_array($result))
{
$rows[] = $row;
}
//Return result to jTable
$jTableResult = array();
$jTableResult['Result'] = "OK";
$jTableResult['TotalRecordCount'] = $recordCount;
$jTableResult['Records'] = $rows;
return $jTableResult;
}
When i load the controller page, the error message from jtable occured "An error occured while communicating to the server". Please help. thanks.
Why your using jtable .can you use Jquery Datatbles here having ignited Datatables Library using that one we can implement crud functionality simple
you can interest please check it once the bellow url
https://github.com/IgnitedDatatables/Ignited-Datatables/
http://datatables.net/examples/data_sources/server_side.html
https://ellislab.com/forums/viewthread/160896/
i am personal y like jquery data-tables.just check it once
First load view page in separate function .In that page you call call your crud Urls
Change like this your controller
function list()
{
$this->load->view('Attendance_view');
}
function listRecord()
{
$this->load->model('Attendance_action');
$jTableResult=$this->Attendance_action->list_record();
print_r(json_encode($jTableResult));
}
Note : Can you please check it once this here mentioned clearly how to implement this one
http://jtable.org/GettingStarted
i want to share my code. Now the problem fixed. I just change the controller code like this. Add "exit();" in controller.
function index()
{
$this->load->view('Attendance_view');
}
function listRecord()
{
$this->load->model('Attendance_action');
$jTableResult=$this->Antendance_action->list_record();
print_r(json_encode($jTableResult));
exit();
}

Yii CgridView bulk delete

In many of my Models' CgridViews I have a bulk delete function: a chechboxColumn and a delete button which deletes all the checked users. For that I am using ajax in the admin and a new action in the controller.
All this works fine until I add pagination to th gridview, which is not saving the checked rows in the previous pages.
I tried to use
'enableHistory'=true,
but it did nothing (and from what I'v read I'm not the only one :mellow: ) , so I downloaded this extension: selgridview
The extension works - when I move through the pages , the checked rows stay checked BUT , my bulk delete function is seeing only the checked rows of the page I'm in right now.
this is the ajax I'm using:
<?php
Yii::app()->clientScript->registerScript('delete','
$("#butt").click(function(){
var checked=$("#person-grid").yiiGridView("getChecked","person-grid_c11");
var count=checked.length;
if(count>0 && confirm(" are you sure you want to delete "+count+" people ? "))
{
$.ajax({
data:{checked:checked},
url:"'.CHtml::normalizeUrl(array('person/remove')).'",
success:function(data){$("#person-grid").yiiGridView("update",{});},
});
}
});
');
?>
Now , maybe thats a silly question but I know little about javascript.
I'm not even sure that the problem is in the ajax . . . .
Help would be much appreciated :rolleyes:
I am using selgridview extension.
Here is my code for deleting the selected users
//delete multiple users at once
$('#delete_selected_items_button').on('click', function () {
var selected = $("#users-grid").selGridView("getAllSelection");
//if nothing's selected
if ( ! selected.length)
{
alert('Please select minimum one user to be deleted');
return false;
}
//confirmed?
if ( ! confirm('Are you sure to delete ' + selected.length + ' users?')) return false;
var multipledeleteUrl = "<?php echo Yii::app()->baseUrl;?>/users/multipledelete";
$.ajax({
type: "POST",
url: multipledeleteUrl,
data: {selectedUsers : selected},
success: (function (e){
//just to make sure we delete the last selected items
$("#users-grid").selGridView("clearAllSelection");
//we refresh the CCGridView after success deletion
$.fn.yiiGridView.update("users-grid");
}),
error: (function (e) {
alert("Can not delete selected users");
})
});
})
On UsersController, actionMultipleDelete() do something like this
if (Yii::app()->request->isAjaxRequest)
{
$selectedUsers = Yii::app()->request->getPost('selectedUsers');
//iterate through all ids
foreach ($selectedUsers as $id)
{
//delete the user here...
}
}
I don't know about this plugin and how it saves what checkboxes are
checked, but you can look into that and then send that information
to your controller.
Alternatively you can save which models should be
deleted in a session. On a checkbox click() (check if the check box is checked
or unchecked) event call your controller with ajax to save the
model's id in your session. then when the user clicks delete you can
retrieve this data from the session.

Joomla - OnMouseover show data from controller in tooltip using Qtip script

I need help to show the data (from controller) in tooltip (using qTip script) on MouseOVer event.
User mouserover on link (Multiple links like in foreach)
id send to a js function like function getData(id){}
Call the PHP function from the controller & using the variable return the data to tooltip.
Show return data into tooltip.
HTML & PHP:
foreach ($rows as $row) {
<a href="#" onmouseover="getData(<?php echo $row->id; ?>)" >Name</a>
}
JS function :
function getData(id)
{
var url='index.php?option=com_test&controller=test&task=getDetails&format=raw';
var data = 'item_id=' + id ;
var request = new Request({
url: url,
method:'post',
data: data,
async: true,
onSuccess: function(responseText)
{
// How i show the "responseText" data here in tooltip using qTip
}
}).send();
}
Controller function:
function getDetails()
{
echo $return = JRequest::getVar('item_id');
}
Would it not be easier to preload the tip in a content item view override (add it to the title= attribute), and adding the call to qTip (one per page) would do the trick.
Also, ajax would make the tooltip not very quick.
Just make sure you properly escape " or ' characters in the title attribute or you will break your markup.
edit: added code. i'm writing this here so there may be typos, but it should give you the idea:
foreach ($rows as $row) {
// let's assume $tip contains the right tip for each row:
Name
}
This first part will show the default browser tooltip.
Now you have to inject the qTip script:
$document = JFactory::getDocument();
$document->addScriptDeclaration('
jQuery("a.tipme").qTip();
');
Now how to put the value in $tip? I see you have a com_test component, you don't need to go through the controller, but can instantiate directly the model that will provide the tooltip; if it's called "tip":
$tipmodel=JModel::getInstance('tip', 'ComtestModel'); // get the model (once!)
$tip = $tipmodel->getTip($row->id);
All the variable, model, controller names in this story are fictional.

Zend Form: onchange select load another view content

In my application I have a form in controller/index that consists out of 3 select boxes. When all three boxes have a value selected I need to show additional html and extra form options in the same view based on those select values. The obvious solution seems to make an ajax call to another action that handles the database operation and creates a view and loading that view into the controller/index.phtml
I have been able to load a view of another action in the index.phtml by using:
$('#select').change(function() {
event.preventDefault();
var id = $(this).attr('id');
$('#results').show();
$('#results').load('/controller/index/' + $(this).attr('value'));
return false;
});
However I need to pass the variables of all three select boxes and for that I alternatively used:
$('#select1').change(function() {
var select1 = $('#select1').val();
var select2 = $('#select2').val();
var select3 = $('#select3').val();
$.ajax({
type: 'POST',
dataType: 'json',
url: '/controller/index/',
data: { select1: select1, select2: select2, select3: select3},
success: function(result){
var return1 = result.return1;
var return2 = result.return2;
}
});
});
The last method works in as far that I do see the variables passed in the headers and the response contains the view, but I cant fix it that just the content of the ajax view is placed within the index view. (Ofcourse by not using AjaxContent switching, the ajax view will load but that includes the complete layout as well.) Anything that I echo in the ajax action or ajax view do not show in the index view. Any pointer would be more than welcome
EDIT
the ajax action now looks like
$this->view->layout()->disableLayout();
$this->_helper->viewRenderer->setNoRender(true);
$select1 = $this->_request->getParam('select1');
$select2 = $this->_request->getParam('select2');
$select3 = $this->_request->getParam('select3');
// DO THE OTHER STUFF AND LOGIC HERE
$results = array(
'return1' => 'value1',
'return2' => 'value2'
);
$this->_response->setBody(json_encode($results));
and the controller init
public function init() {
$ajaxContext = $this->_helper->getHelper('AjaxContext');
$ajaxContext->addActionContext('ajax', 'json')->initContext();
}
So everything works, I can see the returned values in the response by using developer tool (network) in my browser, however I just do not know how I can use this to "update" the view
You can do two things:
You can enable the layout of the action you are calling via ajax. See you have disabled layout so even if the view phtml file of the ajax action contains something, it won't show. You can enable layout, use text/html dataType instead of json and show the returned HTML somewhere.
Or, in the success event of the ajax call, write javascript codes to update DOM.
Thanks #Salman for your suggestions as they lead me in the right direction and I managed to solve the problem.
I managed to pass multiple parameters with the ajax .load() call by passing them as get parameters.
The results of the ajaxAction could then be formatted in the ajax.ajax.phtml view and were consecutively
shown within the #results div that resides in the index.phtml where the select boxes are.
controller/index.phtml
<div id="results" style="display:block;">Select all three values</div>
IndexController init and ajaxAction
public function init() {
$ajaxContext = $this->_helper->getHelper('AjaxContext');
$ajaxContext->addActionContext('ajax', 'html')->initContext('html');
}
public function ajaxAction() {
$select1 = $this->_request->getQuery('select1');
$select2 = $this->_request->getQuery('select2');
$select3 = $this->_request->getQuery('select3');
$form = new Application_Form();
// Database operations and logic
$this->view->form = $form;
$this->view->array = $somearray;
}
}
jquery script in index.phtml
$(document).ready(function(){
$('.selector').change(function() {
var select1 = $('#select1').val();
var select2 = $('#select2').val();
var select3 = $('#select3').val();
if ( select1 && select2 && select3) {
$('#results').show();
$('#results').load('/controller/ajax?select1=' + select1 + '&select2=' + select2 + '&select3=' + select3);
}
});
});
controller/ajax.ajax.phtml
<?php if ( $this->array ) : ?>
<?php echo( $this->form ); ?>
<?php else: ?>
Nothing found for selected values
<?php endif ?>

Resources