Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP Codeigniter ; Preventing form resubmit

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.

like image 739
Chinthu Avatar asked Dec 20 '13 07:12

Chinthu


3 Answers

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');
}
like image 168
lyhong Avatar answered Nov 04 '22 23:11

lyhong


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') ) 
{...} 
like image 30
idrisjafer Avatar answered Nov 04 '22 22:11

idrisjafer


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');
  }
}
like image 20
Manish Patel Avatar answered Nov 04 '22 22:11

Manish Patel