Reload current URL in Codeigniter After Submit The Form - php

I have one form in my view.php file. Its URL like https://example.com/members/view/1, https://example.com/members/view/2 etc. When I submit form its calling model through controller like below
public function insert_comments(){
$data=$this->input->post();
$this->load->model('work_model');
$result=$this->work_model->insert_comments($data);
if($result)
{
$this->session->set_flashdata('insert_comments','your comments succesfully');
$this->session->set_flashdata('succesfully','alert-success');
$this->load->view('add_coments');
}
else{
$this->session->set_flashdata('insert_comments','your comments failed');
$this->session->set_flashdata('succesfully','alert-danger');
$this->load->view('add_coments');
}
}
}
and model is like below
public function insert_comments($array)
{
return $this->db->insert('comments',$array);
}
Currently its working fine and on form submit its loding view called add_comments, instead I want reload/refresh current page. I am not able to get idea of how I can do it, let me know if someone can help me for do it.
Thanks!

According to this answer, in the controller you can use:
redirect($this->uri->uri_string());

use this :
redirect($_SERVER['REQUEST_URI'], 'refresh');

Whenever you are reloading or redirecting a page you should always use the redirect() method instead of loading a view.
Redirection basically uses the header() method of core PHP and redirection will never execute the code blocks written beyond the redirect() method. But in the case of loading the view, it can execute until the end of the code block.
In your code, replace the line $this->load->view('add_coments'); with the redirection to the desired controller
redirect('your-controller','refresh');
I hope that helps you.

Related

Loading a view from controller

I have controller written in CodeIgniter
this->layout->view('pages/dashboard/youtubeupload')
This code is the part of YouTube video upload code. When I try running this Controller independently it works well. After the success, I have to redirect the controller to view as stated in the last line above.
code for the view:
print_r($_SESSION);
echo "<p>You need to <a href='".$_SESSION['authUrl']."'>authorize access</a> before proceeding.<p>";
The question is, how can I redirect from the controller to view in CodeIgniter?
It's hard to understand exactly what is After the success for you, the youtube upload video proccess or the simple execution of the controller? Or other thing that I missed?
Inside the controller you'll have many methods that will renderize any views, according with your validations you have the possibility to present error messages or simple redirect the user for a login page if a authenticate session is missing for example:
if($_SESSION['user'] == NULL) {
redirect('/account/login', 'refresh'); // or other view
} else {
this->layout->view('pages/dashboard/youtubeupload')
}
Can you explain more and post more code?

Codeigniter Controller return to previous page

I'd like to ask you how can I instead of $this->load->view('some_view.php') at the end of controller code, return user to page from where he invoked controller method? Simple return statement is not working.
ie.
public function someMethod($IDCustomer) {
$this->Some_modal->persist($IDCustomer);
// how to return to previous page instead of line after?
// i've used $this->load->view('someView.php');
}
This should help http://www.codeigniter.com/user_guide/libraries/user_agent.html
$this->load->library('user_agent');
if ($this->agent->is_referral())
{
echo $this->agent->referrer();
}
or straight PHP:
redirect($_SERVER['HTTP_REFERER']);
I've found answer on some thread.
In the page that you want to go back to you can do:
$this->session->set_userdata('referred_from', current_url());
Then redirect back to that page
$referred_from = $this->session->userdata('referred_from');
redirect($referred_from, 'refresh');
Tried return redirect()->to($_SERVER['HTTP_REFERER']); , this would work well.
In Codeigniter 4 You can use previous_url() function from url helper
find more https://codeigniter.com/user_guide/helpers/url_helper.html
I've tried header('location:'.$_SERVER['HTTP_REFERER']); and it's working quite well.
Just a one-liner plain old PHP code.
Use the REDIRECT_QUERY_STRING alternative of HTTP_REFERRER:
// set in session redirect back URL in your common is_logged_in function if user is not logged in
$CI->session->set_userdata('redirect_back', $_SERVER['REDIRECT_QUERY_STRING']);
// below code user after successful login in auth.php library
if($this->ci->session->userdata('redirect_back')){
$redirectBackUrl = $this->ci->session->userdata('redirect_back');
$this->ci->session->unset_userdata('redirect_back');
redirect(base_url() . $redirectBackUrl);
}

response and redirect on one return on laravel 4

I want return response that can download and a redirect that can redirect to other page on the same controller function is it possible if so how can I do it if you could show me like this code if i want to download and then redirect to other page. on one controller.
public function handledown()
{
return Response::download(Input::get('book')) & Redirect::action('ViewController#book');
}
You can't return multiple responses like you are trying to do there.
My advice to you would be to return the response download and then redirect to a route you define within a data-redirect attribute on your button etc what ever you use, with jQuery etc.
Another solution can be found here.

Laravel : Load a view after posting

In Codeigniter I used to call the view function after posting data. Like below;
Ex: I have a show_products() function which will display list of products. When a user add a new product I'm posting data into add_product() function. If the process is successful I will not redirect to the products page, instead load the display function inside the add_product() like this:
//Inside the add_product() function
if(success){
$this->show_products();
}
I think, there is no point of reloading the page again. Since we are already in the post function we can straight away set the view after the database insert.
However in laravel I see people redirecting after posting data.
ex:
//Inside the postProduct() function
if(success){
return Redirect::to('products');
}
I tried;
//Inside the postProduct() function
if(success){
$this->getIndex();// this is my product display function
}
but it didn't work.
Do we have a benefit by loading the view in the post function without redirecting every time?
If so how can I achieve the same thing with the laravel?
Thanks a lot!
It's not about the Laravel, instead, it's about a good or right way of doing things. In other words, it's a good programming practice to redirect to another route/page after you successfully submit a form.
Even in CodeIgniter or plain Php I do like this approach and encourage other developers to do that. So, the question is why this redirect is better than directly calling another method from the same request to show another view/page ?
This is the life cycle of the process:
You post a form to a route/action page.
You validate the submitted data and upon successful validation you insert the submitted data in to your database, otherwise you redirect back to that form with errors and old user inputs.
So. assume that, you have submitted a form and done saving the data into database successfully. After you save it you done something like this:
return View::make('...')->with('success', 'Data saved!');
In this case, your user can see the success message on the screen but what if the user, presses the f5 key from the keyboard to refresh the page (probably, accidentally), the form will be submitted to the same action again and the whole process will be repeated again.
So, if you had a redirect after form submission then, refreshing the page won't make any request to that form again.
Google search result on form resubmit on refresh., check the links, may be first one/two, you'll get better idea about the problem and the benefits of redirection after form submission.
in Codeigniter to redirect page we have redirect() function.
if(success){
redirect('products');
}
You don't have to return Redirect. The reason people use it quite often in larvel is because it's comfy.
You can return something else, eg. a view:
return View::make('home.index')->with('var',$var);
In Laravel, to redirect after doing a POST, you could return a redirect with a named route:
return redirect()->route('my-route-name');
Or if you are within the controller that has the route method you want (eg. the index method, you could do this as well:
return self::index();

PHP/codeigniter - use of exit()

I have a few pages that require login, so all controllers that link to these pages start with
$this->checkSession();
//...rest of the code
CheckSession should verify the session is still live, otherwise display a message and stop the execution of the rest of the code in the controller:
function checkSession()
{
if (!$this->session->userdata('is_logged_in'))
{
//the session has expired!
$data['main'] = 'confirmation_message';
$data['title'] = "Session expired";
$this->load->vars($data);
$this->load->view('template');
exit();
}
}
.
I was expecting these instructions to happen in sequence, but I only get a blank page.
How can I make sure exit() gets executed only after all views are loaded?
In this case Pedro is correct. If they are not logged in just redirect them, it's even better if you can use Public/Admin named base controllers to stop you having to do this in each separate protected file.
Generally speaking though, if you use exit() it will stop the Output library for running. If you just want to stop the current controller from executing but allow output of the controller you can use return in exactly the same way.
function checkSession()
{
return (bool) $this->session->userdata('is_logged_in');
}
Then simply:
if(!$this->checkSession())
{
//the session has expired!
$data['main'] = 'confirmation_message';
$data['title'] = "Session expired";
$this->load->vars($data);
$this->load->view('template');
return;
}
exit() should only ever be used if you really want instant death of your application's execution for debugging, error reporting, etc.
In this case you should not use exit, what you should do if the session is not valid is redirect your app using example:
redirect('/init/login/','refresh');
I had a similar problem. Where I wanted to stop the user to due to no login. But I wanted to offer a list of links for them not simply redirect them to a login page. I am using CI version 1.7.2 and the $this->_output() $this->display->_output() and $this->output->_display() solutions did not work for me. I was however to get my results using the $this->output->get_output() function.
$this->load->vars($data);
$this->load->view('template');
die($this->output->get_output());
$this->output->_display();
exit();
Is the correct answer! Thanks to Sam Sehnert... It's hidden in the comments so thought I'd re-post.
I don't know enough about codeigniter's workflow but it seems to me that you want to redirect to the login page instead of trying to render it. Evidently, none of the code you supplied sends the template to the browser by the time exit() is called.
exit() cuts your scrip there and the actual _output() function of the controller is never called. What you need to do is add action in one of your controllers for example the user login screen and redirect there. You can use the flashdata function from the Session - http://codeigniter.com/user_guide/libraries/sessions.html to pass your message and then catch it inside your view and display it.
Another way which is not very smart but should work is to forcefully call the output function.
function checkSession()
{
if (!$this->session->userdata('is_logged_in'))
{
//the session has expired!
$data['main'] = 'confirmation_message';
$data['title'] = "Session expired";
$this->load->vars($data);
$this->load->view('template');
$this->_output();
exit();
}
}
Actually in the newest CI function to manually call output class is
$this->display->_output();
and don't be worried - it handles caching, content will also be properly gzipped if you set so in config
I usually add and extended controller with login logic that handles login functions, so that if a normal controller is one that is needing an auth then the login method is called automatically and the original content is not displayed. It's a good solution if you would like to stay on the page the user tried to access without redirecting (and then posting him back to the same page)
Put the code in a variable and write it.
$html = $this->load->view('template',null,true);
echo $html;
exit();

Categories