Welcome Guest, Not a member yet? Register   Sign In
Question about Login Application Using JQuery Ajax & CodeIgniter
#1

[eluser]Đaяк Đaηтє[/eluser]
Actually I´m doing an login application, really easy, but in this moment I have a situation that I can't solve by myself.

I'm trying to make an Authentication using Jquery's Ajax functionality, but I need that if the authentication is valid, redirect or load another view, like an admin panel or so. Does anyone any idea how to make that? I write the code for my view, controller and model below

View - system/application/views/view_user_login.php
Code:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
&lt;html &gt;
&lt;head&gt;
&lt;meta http-equiv="Content-Type" content="text/html; charset=utf-8" /&gt;
    &lt;title&gt;&lt;?php echo $title; ?&gt;&lt;/title&gt;
    [removed][removed]
    [removed][removed]
    [removed]
        $(document).ready(function(){            
            $('#button_text').click(function(){
                var psw = $("#password").val();
                $('#password').val($().crypt({method:"md5",source:$("#password").val()}));
                var str = $("form").serialize();
                $.ajax({
                    //url: '&lt;?php //echo base_url(); ?&gt;Main/login',
                    url: '&lt;?php echo base_url(); ?&gt;doLogin'    ,
                    type: 'POST',
                    cache: false,
                    data: str,
                    success    :     function(result)
                    {
                        if(result == '0')
                        {
                            $("#errorLogin").attr('innerHTML', '');
                            $("#errorLogin").append(result);        
                            $("#password").val(psw);
                        }
                    }                    
                });
            });
        });
    [removed]
&lt;/head&gt;
&lt;body&gt;
    <div id="main">
        <div id="title">
            <div id="key"></div>
            <div id="session">Iniciar sesi&oacute;n</div>
           </div>
        <div id="line1" class="line"></div>
        &lt;form&gt;
            <div id="login-form">
                 <label for="username">Usuario</label>
                &lt;input type="text" id="username" name="username" /&gt;
                <br />
                <label for="password">Contrase&ntilde;a</label>
                &lt;input type="password" id="password" name="password" /&gt;
            </div>
            <div id="line2" class="line"></div>
            
            <div id="buttons">
                <div id="button_bg_right"></div><div id="button_bg_center" class="buttonOnMouseOut"><div id="button_text" class="button_text">Iniciar sesi&oacute;n</div></div><div id="button_bg_left"></div>
            </div>
        &lt;/form&gt;
    </div>
    <div id="errorLogin">&nbsp;</div>  
&lt;/body&gt;
&lt;/html&gt;

Controller- system/application/controllers/Users.php
Code:
&lt;?php
class Users extends Controller
{
    public function __construct()
    {
        parent::Controller();
    }
    public function doLogin()
    {
        $this->load->model('UsersModel', 'users');
        $where = array('usern'=>$this->input->post('username'),
                       'passw'=>$this->input->post('password'));
        $rs = $this->users->doLogin($where);
        if($rs["logged_in"] == TRUE)
        {
            echo '1';
        }
        else
        {
            echo '0';
        }
    }
}

Model- system/application/models/UsersModel.php
Code:
&lt;?php
if (!defined('BASEPATH')) exit('Bye, bye');
class UsersModel extends Model
{
    public function __construct()
    {
        parent::Model();
    }
    public function doLogin($where)
    {
        $this->db->select('name1, usern, email');
        $this->db->from('usuarios');
        $this->db->where($where);
        
        $rs = $this->db->get();
        //echo $this->db->last_query();
        if ($rs->num_rows() > 0)
        {
            foreach ($rs->result_array() as $row)
            {            
                    $sessuser = array(
                                   'name'=> $row["name1"],
                   'username'=> $row["usern"],
                    'email'=> $row["email"],
                   'logged_in' => TRUE);
            }
        }
        else
        {
                    $sessuser = array(
                                   'name'=>"",
                   'username'=> "",
                    'email'=> "",
                   'logged_in' => FALSE);        
                }
        return $sessuser;
    }
}
?&gt;


Quote:I want to load the admin panel using $this->load->view('adminpanel'); or redirect('adminpanel','refresh'), not using the window dot location with Javascript ...

Thanks in advance!
#2

[eluser]mallcom[/eluser]
Hi, I'm trying to do something similar.

everything works.

create a user in this case.
There's error handling.

It shows up on top of the form.
But i want to "catch" the individual errors, and place them under the field mentioned.

I am thinking to use jquery but don't know how to proceed from here.
How can I catch the individual errors and put them in their <div>

There's one framework(codeigniter) but still a lot off approaches as you can see and what I've seen so far on the forums here.

Here's my view(partial)
Code:
<div class="header">
            <h3>Add User</h3>
            <a class="button" href="&lt;?php echo base_url() ?&gt;user_manager/">&laquo; &nbsp;Back to list </a>
        </div>
        <div class="content">
        
        &lt;form class="basic" id="form" action="&lt;?php echo base_url() ?&gt;user_manager/add" method="post" enctype="multipart/form-data"&gt;&lt;!-- Default basic forms --&gt;
        <div class="inner-form">
              &lt;!--currently showing the errors here--&gt;
            <div class="msg msg-error"><p>&lt;?php echo validation_errors(); ?&gt;
            
</p></div>
          
                <dl>
                
                    <dt><label for="firstname">Firstname:</label></dt>
                    <dd>
                        &lt;input class="txt" type="text" id="firstname" name="firstname" value="&lt;?php echo set_value('firstname'); ?&gt;" /&gt;
                        &lt;!--here the error must show up with help of jquery--&gt;
                        <span id="firstname_error" class="error"></span>
                    </dd>
  <dt></dt>
                    <dd>
                        &lt;input class="button" type="submit" value="Add User" /&gt;
                    </dd>
                </dl>
        </div>
    &lt;/form&gt;

the add part of the user_manager controller :
Code:
function add(){
        
        $data['page_title']    = "Add user";
        
        $this->load->library('form_validation');
        //$this->form_validation->set_error_delimiters('<small>', '</small>');

        // validation rules
        $this->form_validation->set_rules('firstname', 'Firstname', 'required');
        $this->form_validation->set_rules('surname', 'Lastname', 'required');
        $this->form_validation->set_rules('username', 'Username', 'trim|required|min_length[3]|max_length[12]|xss_clean');
        $this->form_validation->set_rules('email', 'E-mail', 'callback_email_check');
        $this->form_validation->set_rules('email', 'E-mail', 'trim|required|valid_email');
        $this->form_validation->set_rules('username', 'Username', 'callback_username_check');
        $this->form_validation->set_rules('email', 'E-mail', 'callback_email_check');
        $this->form_validation->set_rules('password', 'Password', 'trim|required|matches[password2]|md5');
        $this->form_validation->set_rules('password2', 'Password Confirmation', 'trim|required');
        $this->form_validation->set_rules('group_id', 'User Level', 'required');
        $this->form_validation->set_rules('enabled', 'Status', 'required');

        


        if ($this->form_validation->run())
        {
            $newuser = array(
                    'firstname'=>$this->input->post('firstname'),
                    'surname'=>$this->input->post('surname'),
                    'username'=>$this->input->post('username'),
                    'email'=>$this->input->post('email'),
                    'password'=>$this->input->post('password'),
                    'enabled'=>$this->input->post('enabled'),
                    'group_id'=>$this->input->post('group_id')
                    );
            
            $this->users->add($newuser);

            $this->session->set_flashdata('message', 'Done. You have added new user.');            
            redirect('user_manager');
        }
        else
        {    
        
        
            $this->render_admintemplate($data);
            $this->template->write_view('content', 'admin/user_manager/add');
            $this->template->render();
        }

        
        
    
    }
#3

[eluser]Đaяк Đaηтє[/eluser]
You can do that very easy using a JQuery Validation Plugin, just check this one:

http://bassistance.de/jquery-plugins/jqu...alidation/
http://jquery.bassistance.de/validate/demo/

This plugin is very easy to use and configurate... if you want to do a validation with codeigniter maybe you will need to use
Code:
$this->session->set_flashdata('field1','No valid value for this field');
$this->session->set_flashdata('field2','No valid value for this field');
....
and print each data message beside you fields, something like this:
Code:
&lt;?php
          if ($this-> session->flashdata('error'))
          {
              echo '<p id="error" class="error">';
              echo $this->session->flashdata('field1');
              echo '</p>';
          }
          ?&gt;...
#4

[eluser]mallcom[/eluser]
Thx Dante

but this is just client side validation jquery-plugin-validation.
how can this plugin catch the server-side CI form_validation errors?

Any thoughts?




Theme © iAndrew 2016 - Forum software by © MyBB