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.
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 theNOTpart of the query.I adjusted my functionality as follows:
Controller
Model