admin管理员组

文章数量:1026156

I am trying to check the username's validity first before the user hits the submit button using Codeigniter. The status of the username if it is taken or not will just appear beside it.

Here is the JS in the view:

<script type="text/javascript" src="../assets/js/jquery.min.js"></script>
<script type="text/javascript"><!--
 $(document).ready(function() {
    $("#username").blur(function() {
        //remove all the class add the messagebox classes and start fading
        $("#msgbox").removeClass().addClass('messagebox').text('Checking...').fadeIn("slow");
        //check the username exists or not from ajax


        $.post("addpatient/check_user_availability",{ username:$(this).val() } ,function(data) {
            if(data=='no') {
                $("#msgbox").fadeTo(200,0.1,function() {  //start fading the messagebox

                    //add message and change the class of the box and start fading
                    $(this).html('This User name Already exists').addClass('messageboxerror').fadeTo(900,1);
                });

            }
            else {
                $("#msgbox").fadeTo(200,0.1,function() {  //start fading the messagebox

                    //add message and change the class of the box and start fading
                    $(this).html('Username available to register').addClass('messageboxok').fadeTo(900,1);    
                });
            }
        });

    });

});  
</script>


Here is a part of the form in html:

<form method="post" action="addpatient/insert" name="register">
        <table id='addpatient'>
            <tr>    
                <td width=100> Username:
                <td width=150>  <input type='text' id='username' name='username' value="<?php if(isset($_POST['username'])) echo $_POST['username']; ?>" placeholder="5-15 char" pattern=".{5,15}" required>
                <td> <span id="msgbox" style="display:none"></span>
                <td><div id="msgbox"></div>
            </tr>...


Here is the controller:

function check_user_availability()
    {
        $username = $this->input->post('username');

        //  Developed by Roshan Bhattarai 
        //  Visit  for this script and more.
        //  This notice MUST stay intact for legal use


        //this varible contains the array of existing users
        $existing_users=$this->user->get_all_usernames();
        //value got from the get metho
        $user_name= $username;

        //checking weather user exists or not in $existing_users array
        if (in_array($user_name, $existing_users))
        {
            //user name is not availble
            echo "no";
        } 
        else
        {
            //user name is available
            echo "yes";
        }
    }


And this is a function in the model:

function get_all_usernames() {
    $this->db->select('username');
    $this->db->from('users');
    $query = $this->db->get();
    return $query->result();
 }



However, when I run it, it always says that the username is available to register even though the username has been taken already.

Another problem is that it doesn't check the username's validity as the user types in his/her desired username in "real time". What I mean is, the user has to click on the next textfields first before the code checks the validity.

Please help me solve these problems. Thank you!

I am trying to check the username's validity first before the user hits the submit button using Codeigniter. The status of the username if it is taken or not will just appear beside it.

Here is the JS in the view:

<script type="text/javascript" src="../assets/js/jquery.min.js"></script>
<script type="text/javascript"><!--
 $(document).ready(function() {
    $("#username").blur(function() {
        //remove all the class add the messagebox classes and start fading
        $("#msgbox").removeClass().addClass('messagebox').text('Checking...').fadeIn("slow");
        //check the username exists or not from ajax


        $.post("addpatient/check_user_availability",{ username:$(this).val() } ,function(data) {
            if(data=='no') {
                $("#msgbox").fadeTo(200,0.1,function() {  //start fading the messagebox

                    //add message and change the class of the box and start fading
                    $(this).html('This User name Already exists').addClass('messageboxerror').fadeTo(900,1);
                });

            }
            else {
                $("#msgbox").fadeTo(200,0.1,function() {  //start fading the messagebox

                    //add message and change the class of the box and start fading
                    $(this).html('Username available to register').addClass('messageboxok').fadeTo(900,1);    
                });
            }
        });

    });

});  
</script>


Here is a part of the form in html:

<form method="post" action="addpatient/insert" name="register">
        <table id='addpatient'>
            <tr>    
                <td width=100> Username:
                <td width=150>  <input type='text' id='username' name='username' value="<?php if(isset($_POST['username'])) echo $_POST['username']; ?>" placeholder="5-15 char" pattern=".{5,15}" required>
                <td> <span id="msgbox" style="display:none"></span>
                <td><div id="msgbox"></div>
            </tr>...


Here is the controller:

function check_user_availability()
    {
        $username = $this->input->post('username');

        //  Developed by Roshan Bhattarai 
        //  Visit http://roshanbh..np for this script and more.
        //  This notice MUST stay intact for legal use


        //this varible contains the array of existing users
        $existing_users=$this->user->get_all_usernames();
        //value got from the get metho
        $user_name= $username;

        //checking weather user exists or not in $existing_users array
        if (in_array($user_name, $existing_users))
        {
            //user name is not availble
            echo "no";
        } 
        else
        {
            //user name is available
            echo "yes";
        }
    }


And this is a function in the model:

function get_all_usernames() {
    $this->db->select('username');
    $this->db->from('users');
    $query = $this->db->get();
    return $query->result();
 }



However, when I run it, it always says that the username is available to register even though the username has been taken already.

Another problem is that it doesn't check the username's validity as the user types in his/her desired username in "real time". What I mean is, the user has to click on the next textfields first before the code checks the validity.

Please help me solve these problems. Thank you!

Share Improve this question edited Sep 14, 2013 at 2:07 Fionnlagh Endika asked Sep 14, 2013 at 2:00 Fionnlagh EndikaFionnlagh Endika 31 gold badge2 silver badges5 bronze badges 4
  • are you sure $query->result() is an array and not an object? Perhaps you should be returning a result_array(): ellislab./codeigniter/user-guide/database/results.html – Kai Qing Commented Sep 14, 2013 at 2:15
  • Thanks for that! So I tried $query->result_array() but it still says the username is valid all the time. I tried to plug in sample values of the array $existing_users=array('john','jack','carol'); and when I typed these in the textfield, it still says such usernames are valid. – Fionnlagh Endika Commented Sep 14, 2013 at 2:20
  • if you console.log(data) in your success does it give you the expected literal string? You are only checking for 'no' so if anything else is being returned it will say it is available. Including any white spaces or other things that may be passed as the script executes – Kai Qing Commented Sep 14, 2013 at 2:41
  • Following Nil'z's answer, the console prints a yes. – Fionnlagh Endika Commented Sep 14, 2013 at 3:01
Add a ment  | 

2 Answers 2

Reset to default 1

Try this:

function check_user_availability()
{
    $username   = $this->input->post('username');
    $result     = $this->user->get_all_usernames( $username );  #send the post variable to the model
    //value got from the get metho
    $user_name= $username;

    if( $result ){
        echo "no";
    }else{
        echo "yes";
    }
}

function get_all_usernames( $username ) {
    $this->db->select('username');
    $this->db->where('username', $username)
    $this->db->from('users', 1);
    $query = $this->db->get();
    if( $query->num_rows() > 0 ){
        return 0;
    }else{
        return 1;
    }
}

Changes in the script:

$(document).ready(function() {
    $("#username").keyup(function() {
        //remove all the class add the messagebox classes and start fading
        $("#msgbox").removeClass().addClass('messagebox').text('Checking...').fadeIn("slow");
        //check the username exists or not from ajax

        var name    = $(this).val();
        $.ajax({
            url     : "<?=base_url()?>addpatient/check_user_availability",
            data    : { username : name },
            type    : 'POST',
            success : function(data){
                if( data == '0' ){
                    $("#msgbox").fadeTo(200,0.1,function() {  //start fading the messagebox

                        //add message and change the class of the box and start fading
                        $(this).html('This User name Already exists').addClass('messageboxerror').fadeTo(900,1);
                    });
                }else if( data == '1' ){
                    $("#msgbox").fadeTo(200,0.1,function() {  //start fading the messagebox

                        //add message and change the class of the box and start fading
                        $(this).html('Username available to register').addClass('messageboxok').fadeTo(900,1);    
                    });
                }else{
                    alert("Some error occured! Check Console");
                }
            }
        });
    });
}); 

Controller:

function check_user_availability() {
    $username = $this->input->post('username');

    $this->form_validation->set_rules('username', 'Username', 'required|is_unique[users.username]');

    if ($this->form_validation->run() == FALSE) {
        //user name is not availble
        echo "no";
    } else {
        //user name is available
        echo "yes";
    }
}

Replace your check_user_availability() in controller with above. no need of using your get_all_usernames model.

View documentation for Form_Validation, set_rules

I am trying to check the username's validity first before the user hits the submit button using Codeigniter. The status of the username if it is taken or not will just appear beside it.

Here is the JS in the view:

<script type="text/javascript" src="../assets/js/jquery.min.js"></script>
<script type="text/javascript"><!--
 $(document).ready(function() {
    $("#username").blur(function() {
        //remove all the class add the messagebox classes and start fading
        $("#msgbox").removeClass().addClass('messagebox').text('Checking...').fadeIn("slow");
        //check the username exists or not from ajax


        $.post("addpatient/check_user_availability",{ username:$(this).val() } ,function(data) {
            if(data=='no') {
                $("#msgbox").fadeTo(200,0.1,function() {  //start fading the messagebox

                    //add message and change the class of the box and start fading
                    $(this).html('This User name Already exists').addClass('messageboxerror').fadeTo(900,1);
                });

            }
            else {
                $("#msgbox").fadeTo(200,0.1,function() {  //start fading the messagebox

                    //add message and change the class of the box and start fading
                    $(this).html('Username available to register').addClass('messageboxok').fadeTo(900,1);    
                });
            }
        });

    });

});  
</script>


Here is a part of the form in html:

<form method="post" action="addpatient/insert" name="register">
        <table id='addpatient'>
            <tr>    
                <td width=100> Username:
                <td width=150>  <input type='text' id='username' name='username' value="<?php if(isset($_POST['username'])) echo $_POST['username']; ?>" placeholder="5-15 char" pattern=".{5,15}" required>
                <td> <span id="msgbox" style="display:none"></span>
                <td><div id="msgbox"></div>
            </tr>...


Here is the controller:

function check_user_availability()
    {
        $username = $this->input->post('username');

        //  Developed by Roshan Bhattarai 
        //  Visit  for this script and more.
        //  This notice MUST stay intact for legal use


        //this varible contains the array of existing users
        $existing_users=$this->user->get_all_usernames();
        //value got from the get metho
        $user_name= $username;

        //checking weather user exists or not in $existing_users array
        if (in_array($user_name, $existing_users))
        {
            //user name is not availble
            echo "no";
        } 
        else
        {
            //user name is available
            echo "yes";
        }
    }


And this is a function in the model:

function get_all_usernames() {
    $this->db->select('username');
    $this->db->from('users');
    $query = $this->db->get();
    return $query->result();
 }



However, when I run it, it always says that the username is available to register even though the username has been taken already.

Another problem is that it doesn't check the username's validity as the user types in his/her desired username in "real time". What I mean is, the user has to click on the next textfields first before the code checks the validity.

Please help me solve these problems. Thank you!

I am trying to check the username's validity first before the user hits the submit button using Codeigniter. The status of the username if it is taken or not will just appear beside it.

Here is the JS in the view:

<script type="text/javascript" src="../assets/js/jquery.min.js"></script>
<script type="text/javascript"><!--
 $(document).ready(function() {
    $("#username").blur(function() {
        //remove all the class add the messagebox classes and start fading
        $("#msgbox").removeClass().addClass('messagebox').text('Checking...').fadeIn("slow");
        //check the username exists or not from ajax


        $.post("addpatient/check_user_availability",{ username:$(this).val() } ,function(data) {
            if(data=='no') {
                $("#msgbox").fadeTo(200,0.1,function() {  //start fading the messagebox

                    //add message and change the class of the box and start fading
                    $(this).html('This User name Already exists').addClass('messageboxerror').fadeTo(900,1);
                });

            }
            else {
                $("#msgbox").fadeTo(200,0.1,function() {  //start fading the messagebox

                    //add message and change the class of the box and start fading
                    $(this).html('Username available to register').addClass('messageboxok').fadeTo(900,1);    
                });
            }
        });

    });

});  
</script>


Here is a part of the form in html:

<form method="post" action="addpatient/insert" name="register">
        <table id='addpatient'>
            <tr>    
                <td width=100> Username:
                <td width=150>  <input type='text' id='username' name='username' value="<?php if(isset($_POST['username'])) echo $_POST['username']; ?>" placeholder="5-15 char" pattern=".{5,15}" required>
                <td> <span id="msgbox" style="display:none"></span>
                <td><div id="msgbox"></div>
            </tr>...


Here is the controller:

function check_user_availability()
    {
        $username = $this->input->post('username');

        //  Developed by Roshan Bhattarai 
        //  Visit http://roshanbh..np for this script and more.
        //  This notice MUST stay intact for legal use


        //this varible contains the array of existing users
        $existing_users=$this->user->get_all_usernames();
        //value got from the get metho
        $user_name= $username;

        //checking weather user exists or not in $existing_users array
        if (in_array($user_name, $existing_users))
        {
            //user name is not availble
            echo "no";
        } 
        else
        {
            //user name is available
            echo "yes";
        }
    }


And this is a function in the model:

function get_all_usernames() {
    $this->db->select('username');
    $this->db->from('users');
    $query = $this->db->get();
    return $query->result();
 }



However, when I run it, it always says that the username is available to register even though the username has been taken already.

Another problem is that it doesn't check the username's validity as the user types in his/her desired username in "real time". What I mean is, the user has to click on the next textfields first before the code checks the validity.

Please help me solve these problems. Thank you!

Share Improve this question edited Sep 14, 2013 at 2:07 Fionnlagh Endika asked Sep 14, 2013 at 2:00 Fionnlagh EndikaFionnlagh Endika 31 gold badge2 silver badges5 bronze badges 4
  • are you sure $query->result() is an array and not an object? Perhaps you should be returning a result_array(): ellislab./codeigniter/user-guide/database/results.html – Kai Qing Commented Sep 14, 2013 at 2:15
  • Thanks for that! So I tried $query->result_array() but it still says the username is valid all the time. I tried to plug in sample values of the array $existing_users=array('john','jack','carol'); and when I typed these in the textfield, it still says such usernames are valid. – Fionnlagh Endika Commented Sep 14, 2013 at 2:20
  • if you console.log(data) in your success does it give you the expected literal string? You are only checking for 'no' so if anything else is being returned it will say it is available. Including any white spaces or other things that may be passed as the script executes – Kai Qing Commented Sep 14, 2013 at 2:41
  • Following Nil'z's answer, the console prints a yes. – Fionnlagh Endika Commented Sep 14, 2013 at 3:01
Add a ment  | 

2 Answers 2

Reset to default 1

Try this:

function check_user_availability()
{
    $username   = $this->input->post('username');
    $result     = $this->user->get_all_usernames( $username );  #send the post variable to the model
    //value got from the get metho
    $user_name= $username;

    if( $result ){
        echo "no";
    }else{
        echo "yes";
    }
}

function get_all_usernames( $username ) {
    $this->db->select('username');
    $this->db->where('username', $username)
    $this->db->from('users', 1);
    $query = $this->db->get();
    if( $query->num_rows() > 0 ){
        return 0;
    }else{
        return 1;
    }
}

Changes in the script:

$(document).ready(function() {
    $("#username").keyup(function() {
        //remove all the class add the messagebox classes and start fading
        $("#msgbox").removeClass().addClass('messagebox').text('Checking...').fadeIn("slow");
        //check the username exists or not from ajax

        var name    = $(this).val();
        $.ajax({
            url     : "<?=base_url()?>addpatient/check_user_availability",
            data    : { username : name },
            type    : 'POST',
            success : function(data){
                if( data == '0' ){
                    $("#msgbox").fadeTo(200,0.1,function() {  //start fading the messagebox

                        //add message and change the class of the box and start fading
                        $(this).html('This User name Already exists').addClass('messageboxerror').fadeTo(900,1);
                    });
                }else if( data == '1' ){
                    $("#msgbox").fadeTo(200,0.1,function() {  //start fading the messagebox

                        //add message and change the class of the box and start fading
                        $(this).html('Username available to register').addClass('messageboxok').fadeTo(900,1);    
                    });
                }else{
                    alert("Some error occured! Check Console");
                }
            }
        });
    });
}); 

Controller:

function check_user_availability() {
    $username = $this->input->post('username');

    $this->form_validation->set_rules('username', 'Username', 'required|is_unique[users.username]');

    if ($this->form_validation->run() == FALSE) {
        //user name is not availble
        echo "no";
    } else {
        //user name is available
        echo "yes";
    }
}

Replace your check_user_availability() in controller with above. no need of using your get_all_usernames model.

View documentation for Form_Validation, set_rules

本文标签: