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.
Related
I am working on a project which deals with lots of forms. I searched and tried the search results, but none of them worked.
My code view code "uprofile.php" is as follows:
<form class="form-horizontal" method="post" action='<?php echo base_url() . "home/addnewagency" ?>'>
<div class="form-group">
<label for="company" class="col-sm-3 control-label">New Agency Name:</label>
<div class="col-sm-4">
<input type="text" class="form-control" id="newagency" name="newagency" placeholder="Plase Enter New Agency Name">
</div>
</div>
<div class="form-group">
<div class="col-sm-offset-3 col-sm-9">
<button type="submit" class="btn btn-primary">Add</button>
</div>
</div>
</form>
My Controller "home.php" code is as follows:
public function addnewagency() {
$newagency = $this->input->post('newagency');
$this->dis_model->newagency_model(strtoupper($newagency));
$this->loadprofile();
}
public function loadprofile() {
$data['inscompanyname'] = $this->dis_model->getcompany();
$data['agentname'] = $this->dis_model->getagent();
$data['agencyname'] = $this->dis_model->getagency();
$data['clientname'] = $this->dis_model->getclient();
$data['deptname'] = $this->dis_model->getdept();
$this->load->view('uprofile', $data);
}
when I submit the form, the control is passed to addnewagency() data gets inserted in the database and the URL is http://localhost/dis/home/addnewagency. After getting back to the calling function, it goes to loadprofile() and loads the view uprofile. But, the URL still remains the same. But, I want it as http://localhost/dis/home/login and also want to pass the data. Does anyone have any idea regarding how to achieve this?
All positive suggestion are welcomed...
Thanks in advance...
Now you are calling $this->loadprofile() within addnewagency(). If you want to change URL, you need to use redirect() function of CodeIgniter.
Replace
$this->loadprofile()
with below line of code and it will work for you.
redirect(base_url() . 'home/loadprofile');
if you want to change the url use redirect(base_url() . 'home/loadprofile'); in your controller addnewagency(); as suggested by others and refer this question to know whether you can send data in redirect function or not,
Sending data along with a redirect in CodeIgniter
I found a alternative option to get this done.
You can't change URL string with $this->load->view function but you can redirect to target controller function using redirect method. Before you call redirect, set flash session data using $this->session->set_flashdata that will only be available for the next request, and is then automatically cleared. You can read it from official codeiginter documentation .
Example :
class Login extends CI_Controller {
public function index()
{
if ($this->session->login_temp_data) {
$data = $this->session->login_temp_data;
} else {
$data = array();
$data['name'] = 'Guest' ;
}
$this->load->view('login', $data);
}
public function get_name()
{
$data = [];
$data['name'] = 'John Doe';
$this->session->set_flashdata('login_temp_data', $data);
redirect("login");
}
}
You want to use the redirect() function
At the bottom of your addnewagency() method like so:
public function addnewagency() {
$newagency = $this->input->post('newagency');
$this->dis_model->newagency_model(strtoupper($newagency));
redirect(base_url() . 'home/loadprofile');
}
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 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 );
}
trying to insert form values into database using codeigniter but nothing heppens.
my form is comment_form.php is like,
<?php echo validation_errors(); ?>
<?php echo form_open('news/comment_form'); ?>
Name<input type="text" name="comment_name"></input><br />
Email<input type="text" name="comment_email"></input><br />
Comment<input type="text" name="comment_body"></input><br />
<input type="submit" name="submit" value="Comment it" ></input>
</form>
here's my controller comments.php
class Comments extends CI_Controller
{
public function __construct()
{
parent::__construct();
$this->load->model('comment_model');
}
public function create_comment()
{
$this->load->helper('form');
$this->load->library('form_validation');
//$data['title'] = 'Create a news item';
$this->form_validation->set_rules('comment_name', 'comment_name', 'required');
$this->form_validation->set_rules('comment_email', 'comment_email', 'required');
$this->form_validation->set_rules('comment_body', 'comment_body', 'required');
if ($this->form_validation->run() === FALSE) {
$this->load->view('templates/header', $data);
$this->load->view('news/comment_form');
$this->load->view('templates/footer');
} else {
$this->news_model->set_comment();
$this->load->view('news/success');
}
}
}
and this is my model comment_model.php
class Comment_model extends CI_Model
{
public function __construct()
{
$this->load->database();
}
public function set_comment()
{
//$this->load->helper('url');
//$slug = url_title($this->input->post('title'), 'dash', TRUE);
$datac = array(
'comment_name' => $this->input->post('comment_name'),
'comment_email' => $this->input->post('comment_email'),
'comment_body' => $this->input->post('comment_body')
);
return $this->db->insert('comments', $datac);
}
}
the problem is whenever i submitting the form it returns nothing, like nothing happened.please help.
In your comment_form.php change
echo form_open('news/create_comment');
to
echo form_open('comments/create_comment');
Why? Because the first parameter you give to form_open() is the action parameter. It will open a form tag like <form action="bla">. And news/create_comment is not the correct page you want to call. Your controller is named comments, that's why you put comments/create_comment.
In your comments.php change
$this->news_model->set_comment();
to
$this->comment_model->set_comment();
Why? Just simply pointing to the false model. Maybe a copypaste-error?
In your comment_model.php remove
$this->load->database();
And load it in your config.php (in the libraries array, add 'database').
Why? IMHO this is the more proper solution. You're probably gonna use your database pretty often, so why load that everytime?
If you still encounter problems, then we need more information. What exactly is not working. Do some debugging for us. After you call $this->news_model->set_comment() write var_dump($this->db->last_query());
this->news_model->set_comment()
Should be
this->comment_model->set_comment()
PS: sorry for the formatting. Mobile version doesn't read new lines.
Change :
$this->load->database();
echo form_open('news/comment_form');
$this->news_model->set_comment();
To:
$this->load->library('database');
echo form_open('news/create_comment');
$this->comment_model->set_comment();
It would be better if you load your database library in your autoload.php. Or in your controller's constructor.
In the set_comment function after $this->db->insert('comments', $datac); just echo the query using below command and try running the same query manually in the database, you may come to know the issue.
echo $this->db->last_query();
Get the posted values in controller instead of model and then pass them to model.
Controller function
public function create_comment()
{
$this->load->helper('form');
$this->load->library('form_validation');
$this->form_validation->set_rules('comment_name', 'comment_name', 'required');
$this->form_validation->set_rules('comment_email', 'comment_email', 'required');
$this->form_validation->set_rules('comment_body', 'comment_body', 'required');
if ($this->form_validation->run() === FALSE) {
$this->load->view('templates/header', $data);
$this->load->view('news/comment_form');
$this->load->view('templates/footer');
} else {
$data['comment_name'] = $this->input->post('comment_name'),
$data['comment_email'] = $this->input->post('comment_email'),
$data['comment_body'] = $this->input->post('comment_body')
$this->news_model->set_comment();
$this->load->view('news/success');
}
}
Model function
public function set_comment($data)
{
//$this->load->helper('url');
//$slug = url_title($this->input->post('title'), 'dash', TRUE);
$this->db->insert('comments', $data);
return $this->db->insert_id();
}
EDITS
The above code will work if you follow these steps.
Go to database.php in application/config and provide database connection settings like hostname , username , password and database name.
Then go to autoload.php in application/config and autoload the database library like this
$autoload['libraries'] = array('database');
Also remove the closing tags for input in your html form.
Try testing like this in controller before moving forward
$post = $this->input->post();
echo '<pre>';
print_r($post);
This will ensure you are receiving post data