Codeigniter | Get previous URL and used as back button to previous page - php

I really wonder how can I do this, I have 3 pages that has the same link going to 1 page, now what I want to do is to have 1 button that is intelligently enough to get which of the 3 pages was used to go to that page and used it as it's link going back to that previous page.
Please if anyone who knows how to do this, help me to get out to this chaos. post some code how to do it in codeigniter. Thank you in advance.

By using a simple javascript to achieve previous button like,
Previous

With the url helper loaded, set the current_url in a hidden field say 'refer_from'.
<input type="hidden" name="refer_from" value="<?php echo current_url(); ?>" />
Get this using Input Class and set this on the anchor link
Previous
NOTE: using window.history.go(-1) will fail and throw a js error, if the user some how lands
directly on the "1" last page. window.history will be empty in that case.

In my case jquery back methods means window.history etc,were not working so,I tried this hope this helps you guys.call this method on click. cheers
function redirection()
{
<?php $send=$_SERVER['HTTP_REFERER'];?>
var redirect_to="<?php echo $send;?>";
window.location = redirect_to;
}

In controller add:
$data['back'] = $_SERVER['HTTP_REFERER'];
In view add a button and link to $back.

//to get previous url $_SERVER['HTTP_REFERER'];
<?php $send = $_SERVER['HTTP_REFERER'];?>
var redirect_to="<?php echo $send;?>";
//to redirected to this link
location.assign(redirect_to);
//you can pass static link also to redirected to this link
location.assign('facebook.com');

I don't know the older version, I guess there was such funcionallity but know there is and you should avoid use the accepted answer it may break in many ways.
Know you can use method previous_url.
Just add it where you need and is all done
<div class="container">
<a href="<?= previous_url();?>" class="btn btn-info">
<i class="bi bi-arrow-return-left"></i>
</a>
</div>
Returns the full URL (including segments) of the page the user was previously on.
Due to security issues of blindly trusting the HTTP_REFERER system variable, CodeIgniter will store previously visited pages in the session if it’s available. This ensures that we always use a known and trusted source. If the session hasn’t been loaded, or is otherwise unavailable, then a sanitized version of HTTP_REFERER will be used.
EDIT
Improvements Issue fix
I noticed that the previous_url alone may suit for all scenarios, especially if we have a form which redirects back to the same page; that's because the previous page would be the one that the user was currently, hence will not come back in the desire place (and others solutions would have same issue anyway), a simple solution, and by all means improvable, is the following:
In /app/Controllers/BaseController.php
/// Use this as base redirect
public static $baseRedirect = '/index';
/** #public
* Will check the User position and avoid and URL which aren't desired
* - #example
* Current Page: /news
* Previus : /index
*
* if the user update a form in the current page, which is a POST or GET and the user is
* /news/update and then will go back to the current page now previous_url() will be /news and
* NOT /index , if the user presses back will go to /news again and not /index.
*
* #var array $skip An array with url slugs to check the previous url, if the previous url containts any then skip to fallback
* #var string $baseRedirect : base redirec if fallback is not provided
* #param string|null $fallback use a target url as the desired 'Go Back' URL
*/
public function getPreviousURL(?string $fallback=null)
{
// NOTE: We need the current_url also inside, to check that we don't go back in the same page ;)
$skip = [current_url(), "create", "udate", "delete", "post"];
$prev = previous_url();
foreach($skip as $s) {
if (str_contains($prev, $s)) {
return site_url($fallback ? $fallback : self::$baseRedirect);
}
}
return $prev;
}
Now , in any controller which extends BaseController
class MyController extends BaseController
// ... code
public function view($slug=null)
{
// code
$data = [
// data
'prev' => $this->getPreviousURL(), // this will be available in any Controller
];
echo view('templates/header', $data);
echo view('news/view', $data);
echo view('templates/footer', $data);
}
Additionally you can pass any fallback into the url ;)
$data = [
// data
'prev' => $this->getPreviousURL(fallback: '/home'), // this will be available in any Controller
];
In a view news/view.php
<?php $prev = $prev ??= site_url('/index'); ?>
<div class="container">
<a href="<?= $prev ?>" class="btn btn-info">
G Back <i class="bi bi-arrow-return-left"></i>
</a>
</div>

/*Back button in codeigniter project using jquery */
<button type="button" class="btn btn-primary btn-sm" id= "back">Back</button>
//JQuery of back button
<script type="text/javascript">
$(document).ready(function(){
$('#back').on('click', function(){
<?php $send = $_SERVER['HTTP_REFERER'];?>
var redirect_to="<?php echo $send;?>";
window.location.href = redirect_to;
});
});
</script>

Related

How to pass data from anchor tag in laravel?

I currently have a form in laravel on whos submission the following methods run:
public function validateSave() {
$qualitycheck = new QualityCheck();
$qualitycheck['site-name'] = Request::input('site-name');
$qualitycheck['favicon'] = Request::has('favicon');
$qualitycheck['title'] = Request::has('title');
$qualitycheck['image-optimization'] = Request::has('image-optimization');
$qualitycheck->save();
Session::flash('quality-data', $qualitycheck);
return redirect('/');
}
So i have the below line that passes the data to the next page:
Session::flash('quality-data', $qualitycheck);
But what i would really want to do is, when the form is submitted, i would really just want to show a link on the next page , which will be coded like so:
#if(Session::has('quality-data'))
Submited Quality Check
#endif
Now on click on the link , i would like to show a view with all the data that the user submitted in the form , How do i do this ? I.E. How do i pass the data form from the <a> to the view that will show up when clicked on the <a> ??
So just to put things into perspective, this is how it works now:
STEP-1 :: User submits form , data is flashed to next page.
STEP-2 :: Data user submits is shown on this page.
How i want it to work is:
STEP-1 :: User submits form , data is flashed to next page.
STEP-2 :: A link is shown to the user(Only if user clicks on the link we move to the next step).
STEP-3 :: Data user submited in first step is shown on this page.
Next time you code, please follow the below coding practices.
Prefer using create() function of model.
Put all your request data that is to be used in one variable (like $input)
Prefer using route names like route('route.name') instead of strings inside redirection() function.
Please replace your function with
public function validateSave() {
$inputs = [
'site-name' => request()->get('site_name'),
'favicon' => request()->has('facvicon'),
'title' => request()->has('title'),
'image-optimization' => request()->has('image-optimization')
]);
$qualityCheck = QualityCheck::create($inputs);
$flashMessage = '<a href=' . route('quality.check.show', $qualityCheck) . '>Submitted Quality Check</a>'
Session::flash('quality-data', $flashMessage);
return redirect(route('home.index'));
}
And ensure you have something like this in your routes file.
Route::get('quality-check/{id}', 'QualityCheckController')->name('quality.check.show');
Let me know if something doesn't work...
try this one.
<a href="{{url('routename')}}">

zend framework $this->url is not working correctly

I am having a link to go to update screen and in the update screen a back button to load the index.
*current url is * http://sample.com/demoZend/public/index/ when i click a post, i take it to this URL, http://sample.com/demoZend/public/index/update/id/1
now there is a button in this view to go back to index.
<?php
$this->title = "Update post";
$this->headTitle('Update Post');
echo $this->form;
?>
Go Back
the problem is, when back button is clicked it goes here, http://sample.com/demoZend/public/index/index/id/1 instead of http://sample.com/demoZend/public/index/index/
This param id is still remaining. id/1 how this param can be removed and make the url to be public/index/index/
I am newbie to zend framework. so this must be a tiny thing for someone who work with zend.
Use the Reset Parameter on the Url Helper, to reset all params
function url(array $urlOptions = array(), $name = null, $reset = false, $encode = true)
echo $this->url(array('controller'=>'index', 'action'=>'index'), null, true);

CodeIgniter Initial Page Load Variable?

I'm looking for a solution to loading the header/footer/navigation only on the initial page view.
The reasoning behind this is that my navigation panel uses Ajax to render the content of the destination link in the main content div instead of actually loading the page itself.
However, I need to be able to say something along the lines of if its the initial view, load the header, navigation, then the actual page, then the footer. But if its not the initial view and the page is loaded in the content div area so for example a navigation link or a form submit, it doesn't load the header, navigation and footer but only the actual page.
So for example I have these 4 views:
header_view
navigation_view
page_a_view
footer_view
And this controller:
controller_a
The navigation has a link which is 'Page A' and points to http://myurl.com/controller_a. If that link is clicked I only wanted controller_a to load the page_a_view view, because the navigation link will load the data of that page into the div.
However if I directly go to http://myurl.com/controller_a, it needs to render the the header/navigation/footer also.
The solution I thought I was on the right lines with was something like a base controller with a function load_page() which would be something like:
function load_page($page, $data) {
if($this->uri->segment($this->uri->total_segments()) == "initial_page_load") {
$this->load->view('header_view');
$this->load->view('navigation_view');
$this->load->view($page, $data);
$this->load->view('footer_view');
} else {
$this->load->view($page, $data);
}
}
So if I was to go to http://myurl.com/controller_a/initial_page_load it would load the header/navigation/footer but if I went to http://myurl.com/controller_a it wouldn't.
However this doesn't cover all possibilities.
Another way I thought of is checking if there is a referring URL, if there is, don't load the header/navigation/footer. But again, this doesn't cover things such as what if the link was referred by an external website?
Does anyone have any suggestions to how I can achieve what I need?
Let this be your view page for all views. For your other pages, you are going to change the content on div, 'page_content' dynamically via ajax.
**application/views/your_template_view.php**
<?php
$this->load->view('header_view');
$this->load->view('navigation_view');
?>
<a href="javascript:void(0)" id='home' class='my_links'>Home</a>
<a href="javascript:void(0)" id='about_us' class='my_links'>About us</a>
<!--
Make sure the id of the page is same as
the file name of view page for respective pages
-->
<div id='page_content'><?php echo $page_content; ?></div>
<?php
$this->load->view('footer_view');
?>
<script lang='javascript'>
$('.my_links').click(function(){
$.post(
'<?php echo site_url('test_controller/get_page_content') ?>',
{'page_content':$(this).attr('id')},
function(response){
if(response != '')
$('#page_content').text(response);
},'json'
);
});
</script>
Let this be your controller :
**application/controller/test_controller.php**
function your_page($param1 = '', $param2 ='') {
/*this one is for your initial page*/
if($param1)
// send mail
if($param2)
// send mail
$data['page_content'] = $this->load->view('initial_page_load');
$this->load->view('your_template_view', $data);
}
function get_page_content()
{
/*this one is for other pages, this provides page content
for the request made from ajax*/
$page_title = $this->input->post('page_title');
$page_content = $this->load->view($page_title);
echo json_encode($page_content);
}
Make a session variable to denote whether the header/footer is loaded, and if it is, just skip them
if (!$this->session->userdata('nav_loaded')) {
$this->load->view('header_view');
}
etc...
This will work for all your pages, no matter where are they called from, provided that all the post-initial calls are done by AJAX.
EDIT
If you want to mix ajax and non-ajax calls after that, the session varable won't work, of course. Perhaps you could put an ajax parameter in your urls and adjust the controllers according to that.
public function index($ajax = false) {
...
if (!ajax) {
$this->load->view('header_view');
}
etc...
}
So, all the AJAX call will have that additional parameter in the url set to true (almost anything except zero: index/1, index/ajax, etc.).
Although I'm still testing this it seems to be doing exactly what I expect so far! It's one of those ones which is simple but does the complete job so hopefully no problems pop up...
In MY_Controller.php
function load_page($page, $data) {
if(!$this->input->is_ajax_request()) {
$this->load->view('header_view');
$this->load->view('navigation_view');
}
$this->load->view($page, $data);
if(!$this->input->is_ajax_request()) {
$this->load->view('footer_view');
}
}
Managed to stumble across that function when looking in the Input class documentation

Remember me checkbox in the joomla ADMIN login Form. How to?

Anyone know how to create a "remember me" checkbox in the joomla ADMIN login form? I am tired to "re-login" everytime that I need to change something in the backend.
I have created the checkbox, but I'm facing some issues to make it work. Thank you in advance
Am I donig something wrong? Still not working.
This is the code I added to the mod_login in default.php "\administrator\modules\mod_login\tmpl\default.php":
<!-- BEGIN - Trying to create Remember me-->
<p id="form-login-remember">
<label for="modlgn-remember"><?php echo 'Remember-me' ?> </label>
<input id="modlgn-remember" type="checkbox" name="remember" class="inputbox" value="yes"/>
</p>
<!-- END - Trying to create Remember me-->
And this is part of the controler:
/**
* Method to log in a user.
*
* #return void
*/
public function login()
{
// Check for request forgeries.
JSession::checkToken('request') or jexit(JText::_('JINVALID_TOKEN'));
$app = JFactory::getApplication();
$model = $this->getModel('login');
$credentials = $model->getState('credentials');
$return = $model->getState('return');
$result = $app->login($credentials, array('action' => 'core.login.admin'));
if (!($result instanceof Exception)) {
$app->redirect($return);
}
parent::display();
}
You just Need to create a check box with name remember.
It will do the rest. when the admin login form submit the corresponding task is written on the
administrator/compoenets/com_login/controller.php
You can find a function with name login()
Just check that code something like this.
$options['remember'] = JRequest::getBool('remember', true);
Also make sure cookie path are correct ,If you are working with subdomain sometime path will create issue.
Hope this may help you..
You can try This plugin to keep alive the session, but is limited too.

how to ajaxify zend_pagination results (already working with partialoop) using jquery

in the controller i have :
$paginator = Zend_Paginator::factory($mdlPost->getPosts($this->moduleData->accordion, 'name ASC'));
if(isset($params['cities'])) {
$paginator->setCurrentPageNumber(intval($params['cities']));
}
$paginator->setItemCountPerPage(4);
$this->view->posts = $paginator;
in the view's i have some thing like this :
if ($this->posts != null) {?>
<div id="cities_accord" class="news">
<?php echo $this->partialLoop('partials/post-min.phtml', $this->posts); ?>
</div>
<?php echo $this->paginationControl($this->posts,
'Sliding',
'public/pagination_cont.phtml');
}
the partial/post-min.phtml
<?php
$color = array(1=>'spring',2=>'summer',3=>'autumn',4=>'winter');
?>
<div id='<?php echo $color[$this->partialCounter] ?>' class="accordion_post">
<?php
$link = Digitalus_Uri::get(false, false, array('openCity' =>
$this->id));//$color[$this->partialCounter]));
?>
<h1 class="accordion_post_title"><?php echo $this->title ?></h1>
<p><?php echo $this->teaser ?> <i>read more</i></p>
</div>
the pagination_cont.phtml taken from this link zend ( http://framework.zend.com/manual/en/zend.paginator.usage.html )
will show links that will pass params to the controller to fetch the corresponding whole page which is working alright for now
but i want to change this so that i will be able ajaxify the returned ( i.e. only a single paginated value rather than reloading the whole page ) results how can i do that using jquery and what should i change ..
** EDIT: it would be nice to have a fail-save ,if possible, for browsers(users) that disabled javascript to see the same thing by reloading the page (i.e. keeping the current status for if(javascript_not_enabled ))**
This is what I've done in the past.
First, setup the AjaxContext action helper to enable the html context on your controller action.
Add a .ajax.phtml view that just contains the section of markup that may be replaced via AJAX as well as the pagination control links. You can probably just copy this out of your normal view. Replace that section in your normal view with something like
<div id="reloadable-content">
<?php echo $this->render('controller/action.ajax.phtml') ?>
</div>
This will ensure that your initial and any non-AJAX requests will still include the right content. The <div> id is purely for referencing the loadable block in JavaScript.
Also make sure you include your JS file (using headScript) in the normal view only.
Now, in your JS file, unobtrusively add the appropriate event binding to the paginator links. As you'll be replacing the pagination control section in order to reflect the correct current page and other links, it's probably best to do this using the jQuery live binding. I'm also assuming you'll wrap the pagination control with some kind of identifiable element (<div class="pagination-control"> for example)
$('.pagination-control').find('a').live('click', function(e) {
var link = $(this);
$('#reloadable-content').load(link.attr('href'), { format: 'html' });
return false;
});
Keep in mind that in using this method, you will lose the ability to navigate the paged requests using the normal back / forward browser buttons. You will also lose the ability to bookmark pages directly (though you could always provide a permanent link to the current page as part of the AJAX loaded content).
You can use something like the jQuery history plugin if you're really concerned but that will require more client-side work.
Another caveat is that the above will only work with pagination links. If you want to use a form with dropdown page selection, you need to add another event handler for the submission.
GOT IT and big Thanks to #Phil Brown :
in the controller int() change the response type to json
class NewsController extends Zend_Controller_Action
{
public function init()
{
$contextSwitch = $this->_helper->getHelper('contextSwitch');
$contextSwitch->addActionContext('list', 'JSON')
->initContext();
}
// ...
}
public listAtcion() {
// .............
$paginator = Zend_Paginator::factory($mdlPost->getPosts($this->moduleData->accordion, 'name ASC'));
if(isset($params['cities'])) {
$paginator->setCurrentPageNumber(intval($params['cities']));
}
$paginator->setItemCountPerPage(4);
$post = array();
foreach($paginator as $post ) {
$post[] = $post;
}
$this->view->post = $paginator;
#TODO //add a check here for non-ajax requests (#improvment)
$this->view->posts = $paginator;
}
in one of the views (most probably in the pagination_cont.phtml) on the pagination controller add the ajax links
<?= $this->ajaxLink (
$this->url('cities'=>$this->page_num),array('id'=>'div_id','complete'=>'js_method(json_data)','method'=>post) ,array('format'=>'JSON'));
and add a JavaScript function of js_method(json_data) to modify the div with id = 'div_id' with a json data
function js_method(json_data) {
var content = parse.JSON(json_data);
$('#div_id').html('');
//fill it with the reposnse content some thing like $('#div_id').append(content);
}

Categories