我如何检查电子邮件是否存在于用户表与codeinighter和ajax

How to I check if email exist in user table with codeinighter and ajax

本文关键字:用户 codeinighter ajax 于用户 是否 何检查 检查 电子邮件 存在      更新时间:2023-09-26

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

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;
         } 
 }
<<p> 视图/strong>我在视图中添加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调用。

您的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);   
    }