0
votes

I`m using codeigniter3 on my website, i try to make a search button for users but i always get Object not found!

The requested URL was not found on this server. The link on the referring page seems to be wrong or outdated. Please inform the author of that page about the error.

If you think this is a server error, please contact the webmaster. Error 404 localhost Apache/2.4.25 (Win32) OpenSSL/1.0.2j PHP/5.6.30

here is the code:

mycontroller.php

<?php
defined ('BASEPATH') OR exit('No direct script access allowed');

class Mycontroller extends CI_Controller {
    public function index()
    {
        $this->load->library('pagination');
        $this->load->model('mymodel');
        $config = array();
        $config['base_url'] = base_url(). 'mycontroller/index';
        $config['total_rows'] = $this->mymodel->count_actor();
        $config['per_page'] = 10;
        $config['num_links'] = 3;
        //$config['uri_segment'] = 3;

        $config['num_tag_open'] = '<li>';
        $config['num_tag_close'] = '</li>';
        $config['cur_tag_open'] = "<li class='disabled'><li class='active'><a href='#'>";
        $config['cur_tag_close'] = "<span class='sr-only'></span></a></li>";
        $config['next_tag_open'] = '<li>';
        $config['next_tag_close'] = '</li>';
        $config['prev_tag_open'] = '<li>';
        $config['prev_tag_close'] = '</li>';
        $config['first_tag_open'] = '<li>';
        $config['first_tag_close'] = '</li>';
        $config['last_tag_open'] = '<li>';
        $config['last_tag_close'] = '</li>';        

        $this->pagination->initialize($config);
        $page = $this->uri->segment(3);
        $data['actor'] = $this->mymodel->fetch_actor($config['per_page'], $page);
        $data['links'] = $this->pagination->create_links();

        $this->load->view('actor_lists',$data);

    }

    public function search_actor() {
        $this->load->model('mymodel');
        $firstname = $this->input->post('search');

        if(isset($firstname) and !empty($firstname)){
            $data['actor'] = $this->mymodel->search_actor($firstname);
            $data['links'] = '';
            $this->load->view('actor_lists', $data);
        }
        else 
        {
            redirect($this->index());
        }
    }
}
?>

mymodel.php

<?php
defined ('BASEPATH') OR exit('No direct script access allowed');

class Mymodel extends CI_Model {

    public function count_actor()   {
        return $this->db->count_all('actor');
    }

    public function fetch_actor($limit, $offset) {
        $this->db->limit($limit, $offset);
        $query = $this->db->get('actor');
        if($query->num_rows() > 0 ) {
            return $query->result();
        }
        else {
            return $query->result();
        }

    }
    public function search_actor($firstname)    {
        $this->db->select('*');
        $this->db->from('actor');
        $this->db->like('firstname', $firstname);
        $query = $this->db->get();
        if($query->num_rows > 0 )
        {
            return $query->result();
        }
        else 
        {
            return $query->result();
        }
    }
}
?>

actor_lists.php

<head>
	<meta charset="utf-8">
	<title></title>
	<link rel="stylesheet" href="http://bootswatch.com/readable/bootstrap.css">
</head>
<div align="center" id="container">
	<h1>Actor Lists</h1>
	<form class="form-inline" role="form" action="<?php echo base_url().'mycontroller/search_actor'; ?>" method="post">
		<div class="form-group">
			<input type="text" class="form-control" name="search" id="search" placeholder="Cauta dupa nume">
		</div>
		<button type="submit" class="btn btn-info" name="submit">Submit</button>
	</form><br/>
	<table style="width: 978px"; class="table table-striped">
		<thead style="background-color: #2aabd2;">
			<tr>
			<th>Actor ID</th>
			<th>Last Name</th>
			<th>First Name</th>
			<th>Date</th>
			</tr>
		</thead>
		<tbody>
			<?php foreach ($actor as $row) { ?>
			<tr>
				<td><?php echo $row->actorid; ?></td>
				<td><?php echo $row->lastname; ?></td>
				<td><?php echo $row->firstname; ?></td>
				<td><?php echo $row->date; ?></td>
			</tr>
			<?php } ?>
		</tbody>
	</table>
	<?php echo $links ?>
</div>
2
First of all, check if mycontroller/search_actor is accessible from url. Try to make a simple echo and check if method echoing message from browser url. If it is then make sure in config file csrf security must be off. Because you are posting a form with POST and Without CSRF token Codeigniter will not call method if CSRF is enable in Config. If CSRF is off then remove redirect code in else condition because redirect takes string as parameters and you are calling class method within. Good luck :)Nono
still dosent workTerchila Marian
Try to remove 'my' word from controller name and from model name, use something else and give a try... Because Codeigniter use "MY_" for Custome Core Models and Controllers. Also make sure you have index.php removel code by using .htaccess code else use "http:// www.website.com/index.php/controller/method".Nono

2 Answers

0
votes

can you change the NAME mycontroller.php to Mycontroller.php and try once;

0
votes

@Terchilă Marian, Your code is absolutely fine, what you have to do:

Check if, with 'index.php'


1 - Does 'http://localhost/teste/index.php/mycontroller' works?

2 - Does 'http://localhost/teste/index.php/mycontroller/search_actor' works?

If above url working properly & your code executing without any error then it's fine.

Check if, without 'index.php'


1 - Does 'http://localhost/teste/mycontroller' works?

2 - Does 'http://localhost/teste/mycontroller/search_actor' works?

If above url working properly & your code executing without any error then it's fine you don't need to worry about anything. CodeIgniter development all Set to rock!.

If not then:

Create a .htaccess file in your Project Root Folder where index.php exist (Just create a blank text file and rename .htaccess. in windows in folder /teste).

Put below code inside .htaccess file to enable re_write mode

<IfModule mod_rewrite.c>
  RewriteEngine on
  RewriteCond $1 !^(index\.php|resources|robots\.txt)
  RewriteCond %{REQUEST_FILENAME} !-f
  RewriteCond %{REQUEST_FILENAME} !-d
  RewriteRule ^(.*)$ index.php/$1 [L,QSA] 
</IfModule>

Open ./teste/index.php and on top put below code to Set Dynamic Base Url for CodeIginter instead of doing manually inside config file.

/*
|--------------------------------------------------------------------------
| Dynamic Base Url
|--------------------------------------------------------------------------
| Put below code in './index.php' on top
|
*/
    define('APP_URL', ($_SERVER['SERVER_PORT'] == 443 ? 'https' : 'http') . "://{$_SERVER['SERVER_NAME']}".str_replace(basename($_SERVER['SCRIPT_NAME']),"",$_SERVER['SCRIPT_NAME']));

Open ./teste/application/config/config.php & update the settings

/*
|--------------------------------------------------------------------------
| Base Site URL
|--------------------------------------------------------------------------
|
| URL to your CodeIgniter root. Typically this will be your base URL,
| WITH a trailing slash:
|
|   http://example.com/
|
| If this is not set then CodeIgniter will guess the protocol, domain and
| path to your installation.
|
*/
$config['base_url'] = APP_URL;

/*
|--------------------------------------------------------------------------
| Index File
|--------------------------------------------------------------------------
|
| Typically this will be your index.php file, unless you've renamed it to
| something else. If you are using mod_rewrite to remove the page set this
| variable so that it is blank.
|
*/
$config['index_page'] = '';

/*
|--------------------------------------------------------------------------
| Cross Site Request Forgery
|--------------------------------------------------------------------------
| Enables a CSRF cookie token to be set. When set to TRUE, token will be
| checked on a submitted form. If you are accepting user data, it is strongly
| recommended CSRF protection be enabled.
|
| 'csrf_token_name' = The token name
| 'csrf_cookie_name' = The cookie name
| 'csrf_expire' = The number in seconds the token should expire.
*/
$config['csrf_protection'] = FALSE;

It's not recommended to set $config['csrf_protection'] = FALSE; but if you are not using CodeIgniter CSRF Protection Security then set FALSE. Because when you set this TRUE and using Form Submission or Ajax Submission then you must put CSRF Code inside your Form or pass within Ajax Data Parameters e.g.

Form Post:

<form action='<?=base_url("mycontroller/search_actor")?>' method='post'>
<input type="hidden" name="<?php echo $this->security->get_csrf_token_name(); ?>" value="<?php echo $this->security->get_csrf_hash();?>" />
</form>

or, Alter the ./teste/application/config/autoload.php configuration file to autoload the form helper, as shown:

/*
| -------------------------------------------------------------------
|  Auto-load Helper Files
| -------------------------------------------------------------------
| Prototype:
|
|   $autoload['helper'] = array('url', 'file');
*/
$autoload['helper'] = array('form');

inside views,

<?php echo form_open('mycontroller/search_actor'); ?>
// other form elements
<?php echo form_close(); ?>

Ajax Request :

<!-- CSRF Hack , Put this code inside head section, so entire body can access-->
<script type="text/javascript">
//<![CDATA[
window.CSRF = {};
window.CSRF['<?php echo $this->security->get_csrf_token_name(); ?>'] = '<?php echo $this->security->get_csrf_hash(); ?>';
$(function() {
     // Attach csfr data token within each ajax request
     $.ajaxSetup({
        data: window.CSRF
     });
 });
 //]]>
</script>

Mycontroller Controller for testing purpose:

<?php
// No direct Script allowed
defined('BASEPATH') or exit('No direct script access allowed');

/**
 * My Test Controller
 */
class Mycontroller extends CI_Controller
{
    /**
     * [index description]
     * @return [type] [description]
     */
    public function index()
    {
        echo "Yes! CodeIgniter Controller working";
    }

    /**
     * [search_actor description]
     * @return [type] [description]
     */
    public function search_actor()
    {
        echo "Yes! CodeIgniter Method working";
    }
}
/* End of file Mycontroller.php */
/* Location: ./application/controllers/Mycontroller.php */