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!
Related
I'm learning Codeigniter and I have a controller named Admin controller
class Admin extends CI_Controller{
/* skipped */
//This function is used to generate changepassword form
public function changepassword(){
$this->data['sessiondata'] = $_SESSION['logged_in'];
$this->data['mainview'] = 'components/admin/changepassword';
$this->load->view($this->layout, $this->data);
}
//changepassword form will be submitted to this function ('admin/checkpassword')
public function checkpassword(){
$error = array(
'required' => '%s tidak boleh kosong',
'matches' => '%s tidak sama, dumb ass'
);
/* some validations skipped */
if($this->form_validation->run($this) == FALSE){
$this->data['mainview'] = 'components/admin/changepassword';
$this->load->view($this->layout, $this->data);
} else {
$tobesent = array(
"oldpassword" => $this->input->post('oldpassword'),
"newpassword" => $this->input->post('newpassword'),
"verifynewpasswprd" => $this->input->post('verifynewpassword')
);
$this->admincrud->changepassword($tobesent);
$this->data['result'] = "Password sukses diubah";
$this->data['mainview'] = 'components/admin/changepassword';
$this->load->view($this->layout, $this->data);
}
}
}
the result is, each time I go to base_url('admin/changepassword'), fill the provided form and then submit the form, my url changes from base_url('admin/changepassword') into base_url('admin/checkpassword'), which I know came as the result of submitting the form. Also each time I type base_url('admin/checkpassword') directly on my address bar, it opens the form, which I know came as the result of the if-else condition in checkpassword function. My question is, from the security standpoint, is it okay if I keep using this structure? and how can I prevent users from directly accessing base-url('admin/checkpassword') and instead redirecting them to base_url('admin/changepassword') ?
well if you don't want the URL to be changed after submitting the form.
You can use redirect('admin/changepassword'); and since you need to provide
messages accordingly, you can use $this->session->set_flashdata('msg','Your message'); before redirection and use it in view like this:
<?php if($this->session->flashdata('msg') <> NULL){echo $this->session->flashdata('msg');} ?>
Solution to your problem is $_SERVER['REQUEST_METHOD'] if i understood correctly...
For example :-
if($_SERVER['REQUEST_METHOD'] == 'POST')//form method is post
{
//checkpassword code
}
else
{
redirect(base_url('admin/changepassword'));
}
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.
Am working on a codeigniter application.
I have a login.php with the following code
public function index()
{
$this->load->view('login');
}
public function login()
{
$username=$this->input->post('username');
$password=$this->input->post('password');
$data=array(
'username'=>'$username',
'password'=>'$password'
);
if(1){
redirect($this->config->base_url().'admin');
}
else{
redirect($this->config->base_url().'login');
}
}
I have declared login as the default_controller.
I have view login.php which has a login form and submit action to login/login. when I click on submit button.
url-at-the-address-bar expected-url redirected-url
[root] login/login login/login
login/login login/login login/login/login
login/login/login login/login login/login/login/login
and so on. The url keeps adding up.
Tried htaccess. htaccess has effects on this issue. Please help
I used the suggestion by Simo, but it did not work. I finally found the answer by changing the form action to:
<form action="http://localhost/CI/login/login" method="post">
dont use base_url() when redirecting to other contollers, you should change this :
if(1){
redirect($this->config->base_url().'admin');
}
else{
redirect($this->config->base_url().'login');
}
to this :
$is_logged = false; // To replace with login statement.
if($is_logged)
redirect('admin');
else
redirect('login');
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 );
}
I have a form set up in a controller that both loads the form and its previously populated contents from a database and processes the form as needed. The problem is $this->form_validation->run() never evaluates to FALSE, even if rules are not met.
Controller:
public function edit_version($node, $lang)
{
// load form validation class
$this->load->library('form_validation');
// set validation rules
$this->form_validation->set_rules("title|Title|required");
// run validation
if ($this->form_validation->run() !== FALSE)
{
// save input to database
die("validation successful");
}
else
{
// either validation was not passed or no data to validate
// load page edition view and display databse contents
// load page model
$this->load->model("page_model");
// get the page from database
$data["page"] = $this->page_model->get_page($node, $lang);
// load views
$this->load->view("admin/header.php", array("title" => "Edit page no.: $node, $lang version - Admin"));
$this->load->view("admin/pages/edit_page.php", $data);
$this->load->view("admin/footer.php");
}
}
Model:
class Page_model extends CI_Model
{
public function get_page($node, $lang)
{
// load the page
return $this->db->get_where("pages", array("node" => $node, "lang" => $lang))->row();
}
public function save_version($page)
{
$this->db->where("node", $page["node"]);
$this->db->where("lang", $page["lang"]);
$this->db->update("pages", $page);
}
public function search($query)
{
return $this->db->get_where("pages", $query)->result();
}
}
View:
<h2>Edit page</h2>
<?php
// load form helper
$this->load->helper("form");
// open a form
echo form_open("admin/page/{$page->node}/edit/{$page->lang}");
// print validation errors
echo validation_errors();
// title and content fields
echo form_label("Title: ", "title");
echo form_input("title", set_value("title", $page->title));
// aesthetic line break
echo "<br>";
echo form_label("Content: ", "content") . "<br>";
echo form_textarea("content", set_value("content", $page->content));
// save button and close form
echo form_submit("submit", "Save page");
echo form_close();
Thanks in advance.
syntax for setting rule is
$this->form_validation->set_rules('field_name', 'Label', 'rule1|rule2|rule3');
by considering rules your set rule line will be
$this->form_validation->set_rules('title','Title', 'required");
I'm not a CodeIgniter seasoned dev but from documentation is the proper syntax not the following?
$this->form_validation->set_rules("title","Title","required");
As per this link:
http://ellislab.com/codeigniter/user-guide/libraries/form_validation.html#validationrules
Use
$this->form_validation->set_rules("title","Title","required");
instead of this
$this->form_validation->set_rules('title','Title','required');
I have tested this. It works like a Charm.