如何使用codeinighter和ajax检查用户表中是否存在电子邮件

时间:2016-09-23 18:50:21

标签: javascript php jquery ajax codeigniter

我希望用户输入他们的电子邮件,然后单击按钮,然后检查电子邮件是否已存在于数据库中 这是我到目前为止没有成功的尝试

模型

public function email_exists($email) {
        $this->db->select('*'); 
        $this->db->from('users');
        $this->db->where('email', $email);
        $query = $this->db->get();
        $result = $query->result_array();
        return $result;
}

控制器

 function email_exists(){
          $this->load->model('main_model');
          $email = $this->input->post('email');
          $exists = $this->main_model->email_exists($email);
          $count = count($exists);
          echo $count;  
           if (empty($count)) {
                return true;
          } else {
               return false;
         } 
 }

查看 我在视图中添加ajax代码我不确定这是否正确

<input id="about-email" type="email">
<div id="about-you" >enter</div>
<script>
       var email = $("#about-email").val();
       $('#about-you').click(function() {
        $.ajax({
                    type:"post",
                    url: "<?php echo base_url(); ?>index.php/my_controller_name/email_exists",
                    data:{ email:email},
                    success:function(response)
                    {
                        if (response == true) {
                            $('#msg').html('<span>email exists</span>');
                        } else  {
                            $('#msg').html('<span>Value does not exist</span>');
                        }  
                    }
                });
    });
</script>   

上面的ajax代码打破了我在该页面的所有javascript我也在同一页面上进行了另一个ajax调用,因此我不知道是否可以在一个页面上进行2次ajax调用。< / p>

1 个答案:

答案 0 :(得分:1)

你的ajax应该是这样的:

    <script>
       var email = $("#about-email").val();
       var url = <?= base_url("my_controller_name/email_exists") ?>
       $('#about-you').click(function() {
       $.ajax({
                    type:"post",
                    url: url,
                    dataType: "json",
                    data: {email: email},
                    success:function(response)
                    {
                        if (response) {
                            $('#msg').html('<span>email exists</span>');
                        } else  {
                            $('#msg').html('<span>Value does not exist</span>');
                        }  
                    }
                });
        return false;
    });
    </script>

在你的控制器中:

    function email_exists(){
        $email = $this->input->post('email');
        $this->load->model('main_model');
        $exists = $this->main_model->email_exists($email);
        $exists = (count($exists) > 0)? true : false;
        echo json_encode($exists);   
    }