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.
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');
}
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') )
{...}
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');
}
}
Kindly use this:
$post_data = $this->session->userdata('post_data');
if ($post_data == $_POST){
$this->session->unset_userdata('post_data');
redirect(current_url(), 'refresh');
}else{
$this->session->set_userdata('post_data', $_POST );
}
Related
I have a problem on getting post data after submitting a form. What I'm trying to do is that, when the user clicks the submit button, input values stored in the hidden fields will be assigned to a variable into another controller class. However, when I tried to print out the form value, its always giving me NULL
This is my code:
Controller
public function updateOrder(){
$this->form_validation->set_rules('delivery_status_id', 'Delivery Status', 'xss_clean');
$this->form_validation->set_rules('remarks', 'Remarks', 'xss_clean');
$this->form_validation->set_rules('total_amt', 'Total Amount', 'xss_clean');
$data = array('remarks' => $this->input->post('remarks'),
'delivery_status_id' => $this->input->post('delivery_status_id'),
'total_amt' => $this->input->post('total_amt'));
if ($data['delivery_status_id'] == $getDeliveryStatusIdDelivered->row('id'))
{
$this->db->select('*');
$this->db->from('user_has_penalty');
$this->db->where("user_id =" . $this->session->userdata['id']);
$query = $this->db->get();
foreach ($query->result() as $row)
{
$this->db->delete('user_has_penalty', array('user_id' => $this->session->userdata['id']));
$this->db->delete('penalty', array('id' => $row->penalty_id));
}
}else if($data['delivery_status_id'] == $getDeliveryStatusIdCancelled->row('id'))
{
$penalty_amt = $data['total_amt'] / 2;
$data = array('amount' => $penalty_amt);
$this->penalty->insert($data);
$penalty_id = $this->db->insert_id();
//var_dump($penalty_id);
}
var_dump($this->input->post); // Outputs NULL
}
View
...
<?php
$name_c = 'Cancelled';
$query = $this->DeliveryStatus->getDeliveryStatusByName($name_c);
echo form_open('Order_Controller/updateOrder');
?>
<input type="hidden" name="delivery_status_id" value="<?php echo $query->row('id'); ?>"/>
<button type="submit" class="btn btn-danger">YES</button>
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
<?php echo form_close(); ?>
Is there something wrong with the code? Any help would be appreciated
In your form tag, if you do not specify the method it will be get method.
<form action="Order_Controller/updateOrder" method="post">
...
</form>
You are missing the method in your form tag.
form_open('order_Controller/updateOrder', array('method'=>'post'));
Note:
Please use model for database related queries.
Pass the query result to the controller and then to the view.
You can add your validation in configuration. To handle all validation at one place.
// This Will outputs always null
var_dump($this->input->post);
// To Get Value Array from codeigniter input class
var_dump($this->input->post());
method will return the values in $_POST variable
because you are accessing uninitialized property of a object
The correct way to get post variable from codeigniter input class is
$this->input->post() is equivalent to $_POST;
$this->input->post('data') is equivalent to $_POST['data']
I am creating a form in codeignitor and every time I try to submit something the page does nothing in chrome or in firefox gives me this message:
The address wasn't understood
Firefox doesn't know how to open this address, because one of the
following protocols (localhost) isn't associated with any program or
is not allowed in this context.
You might need to install other software to open this address.
In internet explorer it trys to find an application to open the page.
I can access the same address directly but it won't let me do it when I submit the form.
this is the code for the form:
<?php
$hidden = array('account_id' => '1');
echo form_open('post', '', $hidden);
?>
<label for="post">Post:</label>
<input type="text" name="post" id="post"/>
<br/>
<input type="submit" value="post" />
</form>
This is the post controller:
<?php
class Post extends CI_Controller {
public function __construct()
{
parent::__construct();
$this->load->model('posts_model');
$this->load->helper('url_helper');
$this->load->helper('form');
}
function index() {
$data['title'] = "posted";
$this->posts_model->add_post();
$this->load->view('templates/header', $data);
$this->load->view('comment/index', $data);
$this->load->view('templates/footer');
}
}
?>
This is the function in the posts_model:
function add_post() {
$data = array('person_acc_id' => $this-> input -> post('account_id'),
'post' => $this -> input -> post('post'),
'deleted' => 0,
'edited' => 0,
'post_time' => date('Y-m-d H:i:s', time()));
$this -> db -> insert('post', $data);
}
Actually you didn't set any method to form. Means your form action is Wrong.
In your function index() you call the view. So Then its load from in that. So if I click form submit <form> come to POST Controller. So it again execute function index() again. This will run like loop til you fix it.
So what you have to do is.
In controller Create new method to receive data
public function validate_form()
{
#your Form validate Code goes here
}
In view <form> should be
echo form_open('post/validate_form', '', $hidden);
this will act like
<form method="post" accept-charset="utf-8" action="http:/example.com/index.php/post/validate_form" account_id="1" />
To Know about Form Validation
Just check your config.php in application/config, then change your link like this:
$config['base_url'] = 'http://localhost/yourApp/';
I guess your value before is like this:
$config['base_url'] = 'localhost/yourApp/';
My code was actually fine. Once I put it on a real server it works. It would not work with localhost.
I am trying to insert a row to the db using codeigniter.
Model-post.php
class Post extends CI_Model{
function get_posts($num=20, $start=0){
$this->db->select()->from('posts')->where('active',1)->order_by('date_added','desc')->limit($num,$start);
$query=$this->db->get();
return $query->result_array();
}
function get_post($postid){
$this->db->select()->from('posts')->where(array('active' => 1, 'postID'=>$postid))->order_by('date_added','desc');
$query=$this->db->get();
return $query->first_row('array');
}
function insert_post($data){
$this->db->insert('posts',$data);
return $this->db->return_id();
}
Controller-posts.php
class Posts extends CI_Controller{
function __construct(){
parent::__construct();
$this->load->model('post');
}
function index(){
$data['posts'] = $this->post->get_posts();
$this->load->view('post_index', $data);
}
function post($postid){
$data['post']=$this->post->get_post($postid);
$this->load->view('post',$data);
}
function new_post(){
if($_POST){
$data =array(
'title'=>$_POST['title'],
'post'=>$_POST['post'],
'active'=>1
);
$this->post->insert_post($data);
redirect(base_url());
}
else{
$this->load->view('new_post');
}
}
View-new_post.php
<form action="<?php base_url(); ?>posts/new_post" method="action">
<p>Title: <input type="text" name="title"></p>
<p>Description: <input type="textarea" name="post"></p>
<input type="submit" value="Add post">
</form>
Index view-post_index.php
foreach ($posts as $post) { ?>
<div id-="container">
<div><h3><?php echo $post['title']; ?> </h3>
<?php echo $post['post']; ?>
</div>
</div>
<?php
}
The index page shows all the posts from db. On clicking the title it takes to post.php view to show the respective data. This part is fine.
While trying to add a new post in new_post.php it is not reflecting in the db nor showing any error. Also I used redirect_url to redirect to the index page after inserting. So it shows the same available posts. On clicking the title it keeps on adding posts/post to the url repeatedly. Clicking the title once after redirecting the url shows
http://localhost/Codeigniter/posts/posts/post/1
Again on clicking the title it adds
http://localhost/Codeigniter/posts/posts/post/post/1
Can anyone help me? Thanks!
There are numerous issues across the entire application. These are what I found:
Views
Two problems in your new_post view.
You are not echoing out your base_url . You need to replace your form's action attribute.
the method attribute should either have post or get. In this case it should be post
Change it like this:
From this:
<form action="<?php base_url(); ?>posts/new_post" method="action">
To this:
<form action="<?= base_url(); ?>posts/new_post" method="post">
alternatively you can do this:
<form action="<?php echo base_url(); ?>posts/new_post" method="post">
Controller
In your posts controller, your new_post() function should be like this:
function new_post() {
if ($this->input->post()) {
$data = array(
'title' => $this->input->post('title'),
'post' => $this->input->post('post'),
'active' => 1
);
$id = $this->post->insert_post($data);// this is the id return by your model.. dont know what you wann do with it
// maybe some conditionals checking if the $id is valid
redirect(base_url());
} else {
$this->load->view('new_post');
}
}
Model
function insert_post() should not have $this->db->return_id();, instead it should be $this->db->insert_id();
in your model
function insert_post($newpost){
$this->db->insert('posts',$newpost);
// check if the record was added
if ( $this->db->affected_rows() == '1' ) {
// return new id
return $this->db->insert_id();}
else {return FALSE;}
}
any user input must be validated. if you are using Codeigniter then use its form validation and use its input library like:
$this->input->post('title')
an example for blog posts are in the tutorial https://ellislab.com/codeIgniter/user-guide/tutorial/create_news_items.html
otherwise in your controller -- check if the new post id did not come back from the model -- if it did not come back then just go to an error method within the same controller so you don't lose the php error messages.
if ( ! $postid = $this->post->insert_post($newpost); ){
// passing the insert array so it can be examined for errors
$this->showInsertError($newpost) ; }
else {
// success now do something else ;
}
Hmm, pulling my hair out a bit here. Not sure what I am doing wrong, but I can't get my form page to submit properly.
At the moment I don't ask it to actually do anything in the model, so I expect when the form is submitted it to redirect elsewhere, or if there is a validation error (or its the first visit to the page) load the form view.
controller:
public function edit($page )
{
$this->load->helper('form');
$this->load->library('form_validation');
$this->load->helper('url');
$this->load->helper('html');
$data['workout'] = $this->workout_model->get_workout($page);
$data['exercise_list'] = $this->workout_model->get_exercise_list();
$data['sets'] = $this->workout_model->get_sets($data['workout']['id']);
$data['scripts'] = array('templates/script_add_ex','templates/script_add_set');
if(empty($data['workout']))
{
show_404();
}
$this->form_validation->set_rules('woDate', 'Date', 'required'); //Any way here to just say "no blanks?"
if($this->form_validation->run() == FALSE)
{
$data['title'] = 'Edit Workout - '.$data['workout']['datetime'];
$this->load->view('templates/header', $data);
$this->load->view('workouts/edit', $data);
$this->load->view('templates/footer', $data);
}
else
{
$woDate = $this->workout_model->update_workout();
redirect('/workouts/view/'.$woDate);
}
}
Model:
public function update_workout()
{
$woDate = $this->input->post('woDate'); //just simply setting $woDate - is this being returned?
}
So I have a view "mysite.com/workouts/view/ with a table of data in it, and a link to "edit" the page, which takes you to "mysite.com/workouts/edit/
When I submit, I expect vaildation rules to be satisfied (woDate is filled in) and to be redirected back to "mysite.com/workouts/view/"
But instead I get sent to "mysite.com/workouts/edit" with no after "edit", so it throws errors saying that $page is not set, becuase it is not in the URL I guess...But I don't get why it is trying to go back to the edit page when I thought the form submission was valid...
Think this is all it was...thanks to #Loopo for prompting the thought process.
I opened my form initially with
<?php echo form_open('workouts/edit'); ?>
Which would result in:
<form action="mysite.com/workouts/edit" method="post" accept-charset="utf-8">
Which when validating the form, if it needed to go back to the editing page due to unfulfilled validation, didn't know what to 'edit', so I needed to change it to this:
<?php echo form_open('workouts/edit/'.$workout['datetime']); ?>
Outputting:
<form action="mysite.com/workouts/edit/2014-07-09_12:07" method="post" accept-charset="utf-8">
This error was preventing things from working properly, so now, on successful form validation, my redirect works.
Thanks all!
I have a form with some text fields and I have a preview button that needs to submit the form to the same controller. And then in the controller, I need to extract the values and populate a form with these values for the template to see. What is the best way to achieve this? I'm a newbe so please be clear.
Sample controller:
public function myControllerName(sfWebRequest $request)
{
$this->form = new myFormClass();
}
Use <?php echo $form->renderFormTag( url_for('#yourRoutingName'), array('method' => 'POST') ); ?> in your template and change #yourRoutingName to the one pointing to your controller.
Now change your controller to be something like this:
public function myControllerName(sfWebRequest $request)
{
$this->form = new myFormClass();
if ($request->isMethod(sfRequest::POST)
{
$this->form->bind( $request->getParameter( $this->form->getName() ) );
// Check if the form is valid.
if ($this->form->isValid())
{
$this->form->save();
// More logic here.
}
}
}
The $this->form->bind( $request->getParameter( $this->form->getName() ) ); part binds posted data to your form where $this->form->isValid() returns a boolean whether the form is valid or not.
Have you tried this ?
$this->redirect($request->getReferer()); //action
if not, then please try and check if its work for you.
Thanks.