I am new to Codeigniter and I am trying learn it by building simple admin panel.. but in the last days I got stuck on some error:
When I send/submit the login information I get 404 error. here is my controller code:
class Login extends CI_Controller {
public function index()
{
if($this->aauth->is_loggedin()){redirect('/dashboard');}
$this->sign_in();
}
public function sign_in()
{
$this->load->view('header');
$this->load->view('login');
$this->load->view('footer');
}
public function validate()
{
$this->form_validation->set_rules('email', 'Email', 'trim|required|xss_clean|valid_email');
$this->form_validation->set_rules('password', 'Password', 'trim|required|xss_clean');
if($this->form_validation->run() == FALSE){
//Field validation failed. User redirected to login page
$this->load->view('header');
$this->load->view('login');
$this->load->view('footer');
}else{
//Check for database and redirect to private area
redirect('/dashboard');
}
}
}
I've also shared my whole project on github, because its may related to some other file:
https://github.com/shaimoryosef/admin
Please try to help me find what is the problem..
Thanks
Shai
Two thing you need to change
first : in view/login.php
Login is link
`Login`
change to button
<button type="submit" class="btn btn-lg btn-success btn-block">Login</button>
And second put index.php in form_open()
<?php echo form_open('index.php/login/validate'); ?>
This link
Login
is wrong, that's why you are probably getting the 404 error, due to the href attribute which points to index.html.
If you want to submit the form just put a submit button and you will get to login/validate through the form action. My advice is to either use
<?php echo form_submit('mysubmit', 'Submit'); ?>
or
<?php echo echo form_button(array( 'type' => 'submit', 'content' => 'Login')); ?>
functions from form helper. Check the CI user guide and pick whichever suits you best.
I am using cakephps Auth Component to login to my site. When I correctly enter in my username and password, it will log me in. Then when I use loggedIn() to check that I am logged in, it is very inconsistent in returning true.
This is my AppController where I set loggedIn() to a variable to use later:
<?php
App::uses('Controller', 'Controller');
App::uses('File', 'Utility');
App::uses('AuthComponent', 'Component');
class AppController extends Controller {
public $components = array(
'Session',
'Auth'=>array(
'loginRedirect'=> array('controller'=>'users', 'action'=>'index'),
'logoutRedirect'=> array('controller'=>'users', 'action'=>'index'),
'authError' =>"You can't access that page",
'authorize'=> array('Controller')
)
);
//determines what logged in users have access to
public function isAuthorized($user){
return true;
}
//determines what non-logged in users have access to
public function beforeFilter(){
$this->Auth->allow('index','view');
$this->set('logged_in', $this->Auth->loggedIn());
$this->set('current_user', $this->Auth->user());
}
}
And here is a bit of my code where I use 'logged_in'
<?php if($logged_in): ?> //this only returns true some of the time
Welcome <?php echo $current_user['username']; ?>. <?php echo $this->Html->link('Logout', array('controller'=>'users', 'action'=>'login')); ?>
<?php else: ?>
<?php echo $this->Html->link('Login', array('controller'=>'users', 'action'=>'logout')); ?>
<?php endif; ?>
And here is my login():
public function login(){
if($this->request->is('post')){
if($this->Auth->login()){ //this returns true every time
$this->redirect($this->Auth->redirect());
}else{
$this->Session->setFlash('Your username and/or password is incorrect');
}
}
}
I have tried calling $this->Auth->loggedIn() instead of using $logged_in but I get the error that the Auth Helper cannot be found.
Please let me know if there is any more information needed to answer my question.
Move these lines to beforeRender()
$this->set('logged_in', $this->Auth->loggedIn());
$this->set('current_user', $this->Auth->user());
Besides that, nothing seems wrong with your code.
The comment that Auth->login() would always return true only happens when you pass any argument to the login() method, which the code you show doesnt have though.
I am following the guide here to play around with the facebook php sdk, but my little app doesn't work. It keeps staying on the login page.
Here is the controller:
<?php if (!defined('BASEPATH')) exit('No direct script access allowed');
class Facebook_connect extends CI_Controller
{
function __construct()
{
parent::__construct();
$this->load->helper(array('form','url'));
$this->load->library('fb_connect');
}
function index()
{
}
function test()
{
$data['title'] = 'Facebook API Testing';
$data['user_id'] = $this->fb_connect->user_id;
if($data['user_id'])
{
$data['user_profile'] = $this->fb_connect->user;
}
if($data['user_id'])
{
$data['logout_url'] = $this->fb_connect->getLogoutUrl();;
}
else
{
$data['login_url'] = $this->fb_connect->getLoginUrl();
}
$this->template->load('template', 'facebook_connect/test', $data);
}
}
?>
Here is the view:
<h1>php-sdk</h1>
<?php if($user_id): ?>
Logout
<?php else: ?>
<div>
Login using OAuth 2.0 handled by the PHP SDK:
Login with Facebook
</div>
<?php endif ?>
<h3>PHP Session</h3>
<pre><?php print_r($_SESSION); ?></pre>
<?php if($user_id): ?>
<h3>Your Avata</h3>
<img src="https://graph.facebook.com/<?php echo $user_id; ?>/picture">
<h3>Your User Object (/me)</h3>
<pre><?php print_r($user_profile); ?></pre>
<?php else: ?>
<strong><em>You are not Connected.</em></strong>
<?php endif ?>
I get stuck at it and couldn't figure out why.
Use this example provided by facebook:
https://github.com/facebook/php-sdk/blob/master/examples/example.php
But keep your $this->load->library('fb_connect'); and make sure to add $this->fb_connect to any facebook library calls in that example.
It works 100%. Try to just put all the code in the controller to make sure it works, then distribute as needed. Not sure what your problem is, perhaps faulty return url.
OK, I admit it. I'm a CI newbie. I'm doing something really basic wrong and I've been at it for a couple of hours and can't find my error.
I have a controller called login. It's in the resources folder in my controllers folder. It loads a view called login_form. But for the life of me it will not load if I go to domain.com/resources/login or domain.com/resources/index. But I can get to it via a route:
$route['engineering-resources/login'] = "resources/login";
Even when I get to it this way, my form action isn't found. Here is my form:
<?php
echo form_open('resources/login/validate_credentials'); //folder/controller/method. I think this is where my problem is
echo form_input('username', 'Username');
echo form_password('password', 'Password');
echo form_submit('submit', 'Login');
echo anchor('login/signup', 'Create Account');
echo form_close();
?>
The path is my resources folder in my controllers folder, and the controller is the login controller using the validate_credentials method. Here is the pertinent part of my login controller:
class Login extends Controller {
function index()
{
$data['title'] = 'Engineering Resources | Login';
$data['main_content'] = 'resources/login_form';
$this->load->view('templates/main.php', $data);
}
function validate_credentials()
{
$this->load->model('login/membership_model');
$query = $this->membership_model->validate();
if($query) // if the user's credentials validated...
{
$data = array(
'username' => $this->input->post('username'),
'is_logged_in' => true
);
$this->session->set_userdata($data);
redirect('resources/members_area');
}
else // incorrect username or password
{
$this->index();
}
}
The index function works when I use the route, but not when I use the above domain.com paths. I assume that is why it cannot find the validate_credentials method. What am I doing wrong?
Here is main.php
<?php $this->load->view('includes/header.php'); ?>
<?php $this->load->view('includes/nav.php'); ?>
<?php $this->load->view($main_content); ?>
<?php $this->load->view('includes/footer.php'); ?>
$route['engineering-resources/login'] = "resources/login";
This does not route to engineering-resources/login/validate_credentials to resources/login/validate_credentials
You should have something like this:
// not tested
$route['engineering-resources/login/(\S*)'] = "resources/login/$1";
One more thing is that if you are using routes, you should use the routes from your views too..
echo form_open('engineering-resources/login/validate_credentials');
I'm using CakePHP 1.3, and trying to make a simple message posting board with ajax. I'm trying to use the Js helper to submit a form on the index page, then refresh the message board's div to include the new message. This is all on a single page.
I have previously posted on this, but I wanted to rephrase the question and include some updates. The previous question can be seen here How to use Js->submit() in CakePHP?
When I came back to this project after a couple days, I immediately tested and the form worked (sort of). Submitting the form added a message to the database (it didn't display the message, but I haven't attacked that part yet). It worked 2 times, adding 2 messages. Then I opened the controller file and commented out some debug code, and it stopped working. It appears the action is not being called.
Here is my messages_controller.php:
<?php
class MessagesController extends AppController {
function index() {
$messages = $this->Message->find('all');
$this->set('messages',$messages);
}
function add() {
$this->autoRender = false;
$this->Session->setFlash('Add action called');
if($this->RequestHandler->isAjax()) {
$this->Session->setFlash('Ajax request made');
$this->layout = 'ajax';
if(!empty($this->data)) {
if($this->Message->save($this->data)) {
$this->Session->setFlash('Your Message has been posted');
}
}
}
}
}
?>
Here is the index.ctp for my Message class
<div id="guestbook" class="section_box">
<h3 id="toggle_guestbook"><div class="toggle_arrow"></div>Sign our Guestbook</h3>
<?php
echo $this->Form->create('Message');
echo $this->Form->input('name', array('label' => 'From:'));
echo $this->Form->input('text', array('label' => 'Message:'));
echo $this->Js->submit('Post Your Message', array(
'url' => array(
'controller' => 'messages',
'action' => 'add'
),
'update' => '#message_board'
));
echo $this->Form->end();
echo $this->Js->writeBuffer(array('inline' => 'true'));
?>
<div id="message_board">
<?php foreach($messages as $message) { ?>
<div class="message">
<p class="message_txt">
<?php echo $message['Message']['text']; ?>
</p>
<div>
<div class="message_name">
<?php echo $message['Message']['name']; ?>
</div>
<div class="message_date">
<small>
<?php echo $message['Message']['date']; ?>
</small>
</div>
</div>
</div>
<?php } ?>
</div>
</div>
When the submit button is clicked, I can see in the console that a POST is made to http://localhost/messages/add with the correct data. But there doesn't appear to be a response. The flash message "Add action called" is NOT set from the controller (or any of the flash messages, for that matter) and the contents of #message_board are emptied.
If I refresh the page at this point, the SECOND flash message appears ("Ajax request made"), and the contents of the #message_board are restored. However the new message was not saved, its the same 2 messages from before.
I'm stumped. I have a feeling maybe there are bigger issues causing my problem, but I can't see it. Any help would be appreciated.
But there doesn't appear to be a
response ... and the
contents of #message_board are
emptied.
That is because you haven't set what action/view to render. You have to do this manually since you have $this->autoRender set to false. You could use render() to do this. More info can be found at its respective cookbook page.
If you have $this->autoRender set to true, then it'll replace the contents of #message_board with the contents of add.ctp
The flash message "Add action called"
is NOT set from the controller (or any
of the flash messages, for that matter)
I think you have to refresh the page or the part which contains the $this->Session->flash() bit for flash messages to appear.
The fact that the flash message appeared when you refreshed the page means that it did call and run the action.
AFAIK, you can only put/print one message from the flash key in the Messages array. The flash key is where the flash messages are stored by default. Each call to setFlash() will overwrite the flash message set by older calls.
Since only the second flash message was displayed, we could say that it failed at passing at least one of the conditions following the second call to setFlash() in the controller. You might want to put debug($this->data) statements near the conditions related to $this->data to help yourself in debugging your problem.
You could also use debug() to know if your application went through a certain action or path since it will almost always be displayed.
So you could do the following to check if it passed this condition:
if(!empty($this->data)) {
debug('Passed!');
If 'Passed!' will be printed after submitting the form, we would know that it passed that condition.
However the new message was not saved
It might be because $data is empty or it failed at validation. If your $data is not empty, it might have failed at validation and since your form doesn't display the validation errors; you might never have noticed them. One way to know if it passed validation is to do the following:
$this->Message->set($this->data);
if ($this->Message->validates()) {
debug('it validated logic');
} else {
debug('didn't validate logic');
}
Ramon's solutions worked for me. Here's the updated code.
Controller add function
function add() {
$this->autoRender = false;
if($this->RequestHandler->isAjax()) {
$this->layout = 'ajax';
if(!empty($this->data)) {
if ($this->Message->validates()) {
if($this->Message->save($this->data)) {
$this->render('/elements/message_board');
} else {
debug('didn\'t validate logic');
}
}
}
}
}
Heres the add form view:
<?php
echo $this->Form->create('Message');
echo $this->Form->input('name', array('label' => 'From:'));
echo $this->Form->input('text', array('label' => 'Message:'));
echo $this->Js->submit('Post Your Message', array(
'url' => array(
'controller' => 'messages',
'action' => 'add'
),
'update' => '#message_board'
));
echo $this->Form->end();
echo $this->Js->writeBuffer(array('inline' => 'true'));
?>
<?php pr($this->validationErrors); ?>
<div id="message_board">
<?php echo $this->element('message_board'); ?>
</div>
I tried to use the same solution as you used but it's not working. Ajax is ok when I access it directly in the URL, and I have the impression that the click is doing nothing. When I use
<fieldset><legend><?php __(' Run 1');?></legend>
<div id="formUpdateID"><div id="#error-message"></div>
<?php
$orders=array_merge($emptyarray,$orders['r1']['Order']);
echo $this->Form->create('Order');
echo $this->Form->input('id', array('value'=>$orders['id'],'type' =>'hidden'));
echo $this->Form->input('race_id', array('value'=> $orders['race_id'],'type' =>'hidden'));
echo $this->Form->input('driver_id', array('value'=>$session->read('Auth.User.driver_id'),'type' =>'hidden'));
echo $this->Form->input('run', array('value'=>$run,'type' =>'hidden'));
echo $this->Form->input('pm', array('value'=>$orders['pm'],'error'=>$err[$run]));
echo $this->Form->input('pr', array('value'=>$orders['pr'],'error'=>$err[$run]));
echo $this->Form->input('fuel', array('value'=>$orders['fuel'],'error'=>$err[$run]));
echo $this->Form->input('pit', array('value'=>$orders['pit'],'label' => __('Pit on lap '),'error'=>$err[$run]));
echo $this->Form->input('tyre_type', array('value'=>$orders['tyre_type'],'error'=>$err[$run]));
echo $this->Js->submit('Modify', array(
'url' => array(
'controller' => 'orders',
'action' => 'ajax_edit'
),
'update' => '#error_message'
));
echo $this->Form->end();
?>
<?php pr($this->validationErrors); ?>
</div></fieldset>
in view and in controller "orders":
function ajax_edit($id=null){
$this->autoRender = false;
if($this->RequestHandler->isAjax()) {
die(debug('In Ajax'));
$this->layout = 'ajax';
debug('didn\'t validate logic');
}
echo 'hi';
}
None of the messages are displayed.
I have some hard coded JS/ajax before which is not targeting this code part.
I did copy ajax layout in th webroot/view folder.
I can see the AJAX code displayed in formatted source code
<div class="submit"><input id="submit-1697561504" type="submit" value="Modify" /></div> </form><script type="text/javascript">
//<![CDATA[
$(document).ready(function () {$("#submit-1697561504").bind("click", function (event) {$.ajax({data:$("#submit-1697561504").closest("form").serialize(), dataType:"html", success:function (data, textStatus) {$("#error_message").html(data);}, type:"post", url:"\/Webmastering\/form1C\/frame\/orders\/ajax_edit\/1"});
return false;});});
//]]>
</script>
BTW, I start getting bored of the lack of doc in cakephp and its non efficacity to realize task more complicated than just posting a post in a blog. So thank you for your help before I start destroying my computer ;)
I know it's an old topic, but I stumbled acros the same problem in my application, so now I think what Thrax was doing wrong, namely he didn't put echo $this->Js->writeBuffer(array('inline' => 'true')); in the view (or in the layout) file, like Logic Artist did, so the scripts for handling the submit button's click weren't generated.