6
votes

I am creating a search page in my CodeIgniter project. On submit, the form calls the controller function, data is fetched via model function and the resulting array is passed to the view

The problem is that when I refresh the result page the form is resubmitting because the $_POST data is still there in the request headers. How can I avoid that resubmit confirmation message

Following is the code for my form :

<!--form--> 
<form id="find" action="<?php echo base_url()?>search/find" method="post">
    <input type="text" name="search_key" class="tb4" id="search_key" placeholder="Search here"/>
    <input type="button" value="search"/>
</form>

Following is the code for my controller:

 /*
     * function for fetching search results
     * @param void
     * @return void
     */
    public function find()
    {   
        $data['search_result']=$this->search_model->search($this->input->post('search_key'));
        $this->load->view('template/header');
        $this->load->view('pages/search_result',$data);
        $this->load->view('template/footer');
    }

Kindly help me with this.I can't use redirect instead of loading the view since I am bound to pass the result array $data to the view.

3
check whether the request is post and have the post data in the request .Then do loading the results.Else do somthing - Deepu
that is fine....the problem is on refreshing the result page a confirmation message is shown by the browser to resubmit the form - Chinthu

3 Answers

7
votes

Try redirect to itself

public function find()
{   
    $data['search_result']=$this->search_model->search($this->input->post('search_key'));
    if($this->input->post('search_key')) {
        redirect('yourcontroller/find');
    }
    $this->load->view('template/header');
    $this->load->view('pages/search_result',$data);
    $this->load->view('template/footer');
}
3
votes

Simple solution is to have a hidden timestamp field in the form.

<?php echo form_hidden( 'TS', time() ); ?> 

When the form is processed, save this timestamp in the session,

$this->session->set_userdata( 'form_TS', $this->input->post( 'TS' ) ); 

Before processing the form check that two timestamps doesn't match

if ( $this->input->post( 'TS' ) != $this->session->userdata('form_TS') ) 
{...} 
1
votes

IF you want to avoid the resubmit then please after save redirect on same controller like this It can be solved using session. If there is any POST form submit,

ie

if (count($_POST) > 0){
  $this->session->set_userdata('post_data', $_POST );
  redirect('same_controller');
}
else{
  if($this->session->userdata('post_data')){
    $_POST = $this->session->userdata('post_data');
    $this->session->unset_userdata('post_data');
  }
}