Prevent Page/Controller/Method Caching on Clean Codeigniter 2.1.1

I have a activate button in my CMS that allows the user to quickly toggle a active/inactive flag for news articles. When clicked the toggle makes a POST request to the url /news/toggle_active/$id, after which the news_model updates the boolean variable in the database for the specific articles id, and the controller redirects back to the index.

Controller
function toggle_active()
{
    $url = $this->uri->uri_string();
    $last_segment = count($this->uri->segment_array());
    $id = $this->uri->segment($last_segment);

    $row = $this->news_model->set_active($id);

    redirect('news/index', 'refresh');
}
Model
function set_active($id)
{
    $data = array(
           'display_flg' => 'NOT display_flg'
    );

    $this->db->where('id', $id);
    $this->db->update($this->tbl_news, $data);
}

The first time the activate button is clicked it works, but subsequent clicks do nothing. If I close the browser window and re-open the page, the button works again, but only for one click.

I haven't specifically enabled any caching, so I'm not sure whats going on.

If I remove the redirect from the end of the toggle_active() method, and output the current value of the display_flg variable, and POST to /news/toggle_active/$id it appears to do nothing on the first request. However on each subsequent refresh the variable changes values. Why is it not doing anything the first time the link is hit?

I found some people with what seems to be a similar issue over at the codeigniter forums, although there was no solid solution.

Answers


I don't think this was a caching problem in the end. I made two major changes to fix the problem.

Firstly, I not check to see whether or not the database request was successful before redirecting.

I also re-wrote my the models set_active() method. Passing the SET clause as an array to the update functions second parameter wasn't working. I needed to use the set functions third parameter to stop the query from escaping the NOT part of the query.

I adjusted my functionality as follows:

Controller

function show_toggle($id)
{
    if($this->news_model->set_active($id)) 
    {
        redirect('news/index', 'refresh');
    }
}

Model

function set_active($id)
{
    $this->db->where('id', $id);
    $this->db->set('display_flg', 'NOT display_flg', FALSE);
    $query = $this->db->update($this->tbl_news);    

    return $query;
}

Need Your Help

Flask WTF localization with Babel

flask flask-wtforms babel

I've used Flask Babel and have localized my project, but I have a problem with WTF forms, I can't translate the fields shown when field is empty. Any help?

Mocking Static Blocks in Java

java unit-testing mocking static-block

My motto for Java is "just because Java has static blocks, it doesn't mean that you should be using them." Jokes aside, there are a lot of tricks in Java that make testing a nightmare. Two of the m...