phpformscodeigniterhttp-redirect

How to redirect to another page after processing a form submission in CodeIgniter


I have a url that looks like this:

http://localhost/store/mens/category/t-shirts/item/a-t-shirt

I have a class called store and at this point in my application the item function has been called and some data about a product has been output on the page.

I need to allow a user to add the item to a basket. I know CI provides a library to help with this and I've built a simple class that will interact with this library to create the shopping cart functionality.

My problem is that I don't understand how I'm supposed to get the form to submit to my shopping cart class and then return to the current url with all the parameters intact like above. Using form_open():

<?= form_open('cart/addItem',array('class' => 'basketForm')); ?>

submits to the correct class but then I have no mechanism to get back to the product page afterwards.

The only way I can think to do it is to send the url along to the cart class and redirect once the cart stuff is done....or use AJAX...but both seem like hacks to get this working.

Is there a clean way to do this?


Solution

  • Redirect to the referrer page with one of two approaches:

    1. In the Controller only:

    <?php
    class Cart extends CI_Controller {
        public function addItem()
        {
            // ... add to cart here
            redirect($_SERVER['HTTP_REFERER']);
        }
    }
    

    2. From the view, tell the controller where you want it to go after:

    <!-- Form view //-->
    <?= form_open('cart/addItem',array('class' => 'basketForm')); ?>
    <?= form_hidden('next_URI', current_url()); // requires URL_helper ?>
    ...
    <?= form_submit('', 'Add to Cart'); ?>
    <?= form_close(); ?>
    
    
    <?php
    // Controller
    class Cart extends CI_Controller {
        public function addItem()
        {
            // ... add to cart here
            redirect($this->input->post('next_URI'));
        }
    }