Ajax代码不能与codeigniter,PHP一起使用。

时间:2017-03-13 06:03:38

标签: php jquery ajax codeigniter

这里我尝试使用Ajax和Codeigniter登录,但无法获得成功。 这是我的小代码,它不使用ajax但使用表单操作。

这是控制器代码

<?php

    class loginmodal extends CI_Controller{


        function login(){   
            $data['title'] = 'USER AUTHENTICATION';
            $this->load->view("loginmodal", $data);

        }
        function index(){
            echo'<script type="text/javascript> alert("php 0"); </script>"';    
        }
        function login_validation(){

            $this->load->library('form_validation');
            $this->form_validation->set_rules('login_username', 'Username', 'trim|required|alpha|min_length[3]|max_length[30]|xss_clean');
            $this->form_validation->set_rules('login_password', 'Password', 'trim|required|alpha|min_length[3]|max_length[30]|xss_clean');

            if($this->form_validation->run())
            {
                    //true
                    $Uname = $this->input->post('login_username');
                    $Pass  =  $this->input->post('login_password');
                    $url =  $this->input->post('current_loginurl');

                    // model function_exists
                    $this->load->model('include/main_loginmodal');                  
                    if($this->main_loginmodal->can_login($Uname, $Pass))
                    {
                        $session_data = array (
                                'username' => $Uname
                        );
                        $this->session->set_userdata($session_data);
                        //redirect(base_url(). 'article');
                        //$this->session->set_flashdata('redirectToCurrent', base_url());
                        //redirect($this->session->flashdata('redirectToCurrent'));
                        //redirect(base_url()/current_url(), 'refresh');

                        redirect(base_url(). 'loginmodal/enter');

                    }
                    else
                    {
                        $this->session->set_flashdata('error', 'Invalid Username or Password');
                        ;
                        redirect(base_url(). 'article');
                    }
            }
            else
            {
                //false;
                $this->login(); 
                //exit

            }
        }

        function  enter()
        {
            if($this->session->userdata('username') != '')
            {
                redirect(base_url(). 'loginmodal/index');
                //redirect($url);
                echo 'Login Success'.$this->session->userdata('username');
                echo'<script type="text/javascript> alert("php 1"]); </script>"';
            }
            else
            {
                redirect(base_url(). 'loginmodal/article');
                echo'<script type="text/javascript> alert("php 2"]); </script>"';
            }
        }

        function logout()
        {
            $this->session->unset_userdata('username');
            redirect(base_url(). 'loginmodal/index');
        }
    }

?>

这是我的ajax代码..

<script type="text/javascript">
$(document).ready(function(){
         $("#loginform").submit(function(event){
            event.preventDefault(); 

            $.ajax({

                    url: "<?php echo base_url();?>include/loginmodal/login_validation",  
                    type: "POST",
                    data: 
                    {
                        login_username: $('#login_username').val(),
                        login_password: $('#login_password').val()},

                        success: function(data) 
                        {
                            alert(data);
                            if (data !== '')
                            {   
                                alert("you are logged IN");
                                //window.location.replace("http://127.0.0.1/simple_login_redirect/index.php/user/home");
                                //window.location.href="http://127.0.0.1/simple_login_comp/index.php/user/members";
                            }
                            else if(data === ''){

                                alert("sorry");
                            }

                        }

                });
                alert('data is ');
        });
    });
</script>

这是我的观看代码

<!-- -Login Modal -->

    <div class="modal fade" id="loginModal" tabindex="-1" role="dialog" aria-labelledby="loginModalLabel" aria-hidden="true">
        <div class="modal-dialog">
            <div class="modal-content login-modal" style="background-color:#fff;">
                <div class="modal-header login-modal-header" >
                    <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span></button>
                    <h4 class="modal-title text-center" id="loginModalLabel">USER AUTHANTICATION</h4>
                </div>
                <div class="modal-body">
                    <div class="text-center">
                        <div role="tabpanel" class="login-tab">
                            <!-- Nav tabs -->
                                        <ul class="tab">
                                          <li><a href="javascript:void(0)" class="tablinks" onclick="openCity(event, 'home')" id="defaultOpen">SignIn</a></li>
                                          <li><a href="javascript:void(0)" class="tablinks" onclick="openCity(event, 'profile')">SignUp</a></li>
                                          <li><a href="javascript:void(0)" class="tablinks" onclick="openCity(event, 'forget_password')">Forgot Password</a></li>
                                        </ul>

                            <!-- Tab panes -->

                                <div role="tabpanel" class="tab-pane active text-center tabcontent " id="home" style="border:none; vertical-align:middle;" >
                                    &nbsp;&nbsp;
                                    <span id="login_fail" class="response_error" style="display: block;"><?php $this->session->flashdata("error");?></span>
                                    <div class="clearfix"></div>
                                    <form method="post" action="" id = "loginform">
                                    <div class="form-group">
                                            <div class="input-group" style="display : none;">
                                                 <div class="input-group-addon"><i class="fa fa-user"></i></div>
                                                <input type="hidden" class="form-control" id="current_loginurl" name="current_loginurl" placeholder="Username" style="background-color:#fff; color:#000;"
                                                        value="<?php echo current_url(); ?>">
                                            </div>
                                            <span class="help-block has-error" id="email-error"></span>
                                            <?php echo form_error('login_username'); ?>
                                        </div>
                                        <div class="form-group">
                                            <div class="input-group">
                                                <div class="input-group-addon"><i class="fa fa-user"></i></div>
                                                <input type="text" class="form-control" id="login_username" name="login_username" placeholder="Username" style="background-color:#fff; color:#000;">
                                            </div>
                                            <span class="help-block has-error" id="email-error"></span>
                                            <?php echo form_error('login_username'); ?>
                                        </div>
                                        <div class="form-group">
                                            <div class="input-group">
                                                <div class="input-group-addon"><i class="fa fa-lock"></i></div>
                                                <input type="password" class="form-control" id="login_password" name="login_password" placeholder="Password" style="background-color:#fff; color:#000;">
                                            </div>
                                            <span class="help-block has-error" id="password-error"><?php echo form_error('login_password'); ?></span>
                                        </div>

                                            <input type="checkbox" style="float: left; padding-top:10px;">&nbsp;&nbsp; RememberMe</input>
                                            <input type="submit" id="login_btn" class="btn btn-login" data-loading-text="Signing In...." style="float: right;" value="Login">
                                            <span class="help-block has-error" id="password-error"><?php echo form_error('login_password'); ?></span>

                                        <div class="clearfix"></div>
                                        <div class="login-modal-footer">
                                            <div class="row">
                                                <!--<div class="col-xs-8 col-sm-8 col-md-8">
                                                    <i class="fa fa-lock"></i>                                                  
                                                    <a href="javascript:;" class="forgetpass-tab" style="padding-left: 48px;"> Forgot password? </a>                                                
                                                </div>                                              
                                                <div class="col-xs-4 col-sm-4 col-md-4">
                                                    <i class="fa fa-check"></i>
                                                    <a href="javascript:;" class="profile"> Sign Up </a>
                                                </div>-->
                                            </div>
                                        </div>
                                    </form>
                                </div>
                                <div role="tabpanel" class="tab-pane tabcontent" id="profile">
                                    &nbsp;&nbsp;
                                    <span id="registration_fail" class="response_error" style="display: none;">Registration failed, please try again.</span>
                                    <div class="clearfix"></div>
                                    <form method="post" action="">
                                        <div class="form-group">
                                            <div class="input-group">
                                                <div class="input-group-addon"><i class="fa fa-user"></i></div>
                                                <input type="text" class="form-control" id="F_Name" placeholder="First Name"  style="background-color:#fff; color:#000;">
                                            </div>
                                            <span class="help-block has-error" data-error='0' id="username-error"></span>
                                        </div>
                                        <div class="form-group">
                                            <div class="input-group">
                                                <div class="input-group-addon"><i class="fa fa-at"></i></div>
                                                <input type="text" class="form-control" id="L_Name" placeholder="Last Name"  style="background-color:#fff; color:#000;">
                                            </div>
                                            <span class="help-block has-error" data-error='0' id="remail-error"></span>
                                        </div>
                                        <div class="form-group">
                                            <div class="input-group">
                                                <div class="input-group-addon"><i class="fa fa-at"></i></div>
                                                <input type="Email" class="form-control" id="Email" placeholder="Email"  style="background-color:#fff; color:#000;">
                                            </div>
                                            <span class="help-block has-error" data-error='0' id="remail-error"></span>
                                        </div>
                                        <div class="form-group">
                                            <div class="input-group">
                                                <div class="input-group-addon"><i class="fa fa-at"></i></div>
                                                <input type="password" class="form-control" id="r_password" placeholder="Password"  style="background-color:#fff; color:#000;">
                                            </div>
                                            <span class="help-block has-error" data-error='0' id="remail-error"></span>
                                        </div>
                                        <div class="form-group">
                                            <div class="input-group">
                                                <div class="input-group-addon"><i class="fa fa-at"></i></div>
                                                <input type="password" class="form-control" id="rc_password" placeholder="Confirm Password"  style="background-color:#fff; color:#000;">
                                            </div>
                                            <span class="help-block has-error" data-error='0' id="remail-error"></span>
                                        </div>
                                        <button type="button" id="register_btn" class="btn btn-block bt-login" data-loading-text="Registering....">Register</button>
                                        <div class="clearfix"></div>
                                        <div class="login-modal-footer">
                                            <!--<div class="row">
                                                <div class="col-xs-8 col-sm-8 col-md-8">
                                                    <i class="fa fa-lock"></i>
                                                    <a href="javascript:;" class="forgetpass-tab"style="padding-left: 48px;"> Forgot password? </a>

                                                </div>

                                                <div class="col-xs-4 col-sm-4 col-md-4">
                                                    <i class="fa fa-check"></i>
                                                    <a href="javascript:;" class="signin-tab"> Sign In </a>
                                                </div>
                                            </div>-->
                                        </div>
                                    </form>
                                </div>
                                <div role="tabpanel" class="tab-pane text-center tabcontent" id="forget_password">
                                    &nbsp;&nbsp;
                                    <span id="reset_fail" class="response_error" style="display: none;"></span>
                                    <div class="clearfix"></div>
                                    <form method="post" action="">
                                        <div class="form-group">
                                            <div class="input-group">
                                                <div class="input-group-addon"><i class="fa fa-user"></i></div>
                                                <input type="text" class="form-control" id="femail" placeholder="Email"  style="background-color:#fff; color:#000;">
                                            </div>
                                            <span class="help-block has-error" data-error='0' id="femail-error"></span>
                                        </div>

                                        <button type="button" id="reset_btn" class="btn btn-block bt-login" style="padding-left: 48px;"data-loading-text="Please wait....">Forget Password</button>
                                        <div class="clearfix"></div>
                                        <div class="login-modal-footer">
                                            <!--<div class="row">
                                                <div class="col-xs-6 col-sm-6 col-md-6">
                                                    <i class="fa fa-lock"></i>
                                                    <a href="javascript:;" class="signin-tab" style="padding-left: 48px;"> Sign In </a>

                                                </div>

                                                <div class="col-xs-6 col-sm-6 col-md-6">
                                                    <i class="fa fa-check"></i>
                                                    <a href="javascript:;" class="signup-tab"> Sign Up </a>
                                                </div>
                                            </div>-->
                                        </div>
                                    </form>
                                </div>
                        </div>
                    </div>
                </div>

            </div>
       </div>
    </div>

型号代码在这里

<?php

    class main_loginmodal extends CI_Model{

        function can_login($Uname, $pass)
        {
            $this->db->where('Uname', $Uname);
            $this->db->where('Pass', $pass);

            $query = $this->db->get('datab');

            if($query->num_rows() > 0)
            {
                return true;
            }
            else
            {
                return false;
            }
        }

    }

?>

我在控制台中得到了这个错误。 404未找到。

enter image description here

4 个答案:

答案 0 :(得分:0)

您的$ .ajax结构错误。这里添加了示例ajax结构,请更改您的代码结构如下。

          $.ajax({
            url: "<?php echo base_url();?>include/loginmodal/login_validation", 
            method: 'POST',
            data: 'login_username='+$('#login_username').val()+'+&login_password='+$('#login_password').val(),
            success: function(data){
                // Success Code
            },
            error: function(e) {
                    //called when there is an error
                    console.table(e);
            }
          });

答案 1 :(得分:0)

确保您的ajax请求中的网址是正确的。 404表示找不到网址。在截图中,完整网址为:

http://localhost:8080/data/application/controllers/include/loginmodal/login_validation


确保您的base_url已正确定义。

答案 2 :(得分:0)

你的ajax结构:

 $.ajax({
  url : "<?php echo base_url();?>index.php/admin/getclassid",
  dataType: "html",
  type: 'GET',
  data:'classid='+classid,               
   success: function(result) {
   $('#sec').html(result);  
  }
});

您的控制器代码:

   public function getclassdivisionsbyclassid(){
   $classid = $_GET['classid'];
   }

答案 3 :(得分:0)

通过ajax通话,您只能根据您从通话中获得的响应重定向用户。看看我的例子。

// Ajax脚本

$.ajax({
            type: "POST",
            url: your_url,
            data: your_form_data,
            dataType: 'JSON',
            beforeSend: function () {
                // do some animation loading: optional
            },
            success: function (data) {
                if(data.data == TRUE)
                {
                  alert("LogedIN");
                  // redirect user to login page
                }
                else
                {
                   alert('Not Logedin');
                }
            },
            complete: function () {
                // stop loading animation: optional
            }
        });

// PHP脚本 //返回json

if ($this->input->is_ajax_request())
    {

        $response = array(
            'status' => 'OK',
            'data' => your can_login() method results
        );
        $this->output
                ->set_status_header(200)
                ->set_content_type('application/json', 'utf-8')
                ->set_output(json_encode($response, JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES))
                ->_display();
        exit();
    }

你的模型看起来很好,希望它有效