Live username Availability check with AngularJS in CodeIgniter

If there is the registration form on the website then you need to make sure that the username or email must be unique.

The user will login with the selected username next time when it comes to the website.

You can either check it after submitting the form or while entering it.

In the demonstration, I am creating a simple registration form in CodeIgniter where check the entered username with Angular and insert the record if the username is available.

Live username Availability check with AngularJS in CodeIgniter


Contents

  1. Table structure
  2. Configuration
  3. Model
  4. Controller
  5. Download AngularJS
  6. View
  7. Demo
  8. Conclusion

1. Table structure

I am using users table in the demonstration.

CREATE TABLE `users` (
  `id` int(11) NOT NULL PRIMARY KEY AUTO_INCREMENT,
  `username` varchar(60) NOT NULL,
  `name` varchar(60) NOT NULL,
  `email` varchar(80) NOT NULL,
  `password` varchar(60) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

2. Configuration

Navigate to application/config/database.php and define Database connection.

$db['default'] = array(
 'dsn' => '',
 'hostname' => 'localhost',
 'username' => 'root', // Username
 'password' => '', // Password
 'database' => 'tutorial', // Database name
 'dbdriver' => 'mysqli',
 'dbprefix' => '',
 'pconnect' => FALSE,
 'db_debug' => (ENVIRONMENT !== 'production'),
 'cache_on' => FALSE,
 'cachedir' => '',
 'char_set' => 'utf8',
 'dbcollat' => 'utf8_general_ci',
 'swap_pre' => '',
 'encrypt' => FALSE,
 'compress' => FALSE,
 'stricton' => FALSE,
 'failover' => array(),
 'save_queries' => TRUE
);

Default controller

Open application/config/routes.php and edit default_controller value to User.

$route['default_controller'] = 'User';

Load Database

To access the MySQL database require loading database library.

Open application/config/autoload.php and add the database in libraries array().

$autoload['libraries'] = array("database");

3. Model

Create a Main_model.php file in application/models/ directory.

Create 2 methods –

  • checkUsername – This method takes a single parameter of string type.

Count total records available according to the username in users table and return the count.

  • saveUserDetails – This method uses to insert post data in users table.

Firsts check the username is available or not in the users table. If the query returns count 0 then insert a record and return 1 otherwise return 0.

Completed Code

<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');

class Main_model extends CI_Model {

  // Check username
  function checkUsername($username=""){

    // Check username
    $this->db->select('count(*) as allcount');
    $this->db->where('username',$username);
    $user_record = $this->db->get('users');
    $result = $user_record->result_array();

    $allcount = $result[0]['allcount'];
    return $allcount;
  }

  // Insert user
  function saveUserDetails($postdata){

    $name = $postdata->name;
    $username = $postdata->username;
    $email = $postdata->email;
    $password = $postdata->password;

    // Check username
    $this->db->select('count(*) as allcount');
    $this->db->where('username',$username);
    $user_record = $this->db->get('users');
    $result = $user_record->result_array();

    if($result[0]['allcount'] == 0){
       $data = array(
          'username' => $username,
          'name' => $name,
          'email' => $email,
          'password' => $password
       );

       $this->db->insert('users',$data);

       return 1;
    }

    return 0;
  }

}

4. Controller

Create a User.php file in application/controllers/ directory.

Create 4 methods –

  • __construct – Load url helper and Main_model model.
  • index – Load user_view view.
  • checkUsername – This method call from the Angular $http request.

Get the post data and pass in $this->Main_model->checkUsername($username) to check username already used or not and return the response.

  • saveUserDetails – This method is also called from Angular $http request.

Get the post data and pass in $this->Main_model->saveUserDetails($data) and return the response.

Completed Code

<?php
defined('BASEPATH') OR exit('No direct script access allowed');

class User extends CI_Controller {

  public function __construct(){

    parent::__construct();

    // load base_url
    $this->load->helper('url');

    // Load Model
    $this->load->model('Main_model');
  }

  public function index(){

    $this->load->view('user_view');
 
  }

  // Check username availability
  public function checkUsername(){
 
    $data = json_decode(file_get_contents("php://input"));
 
    // Username
    $username = $data->username;

    // Check
    $response = $this->Main_model->checkUsername($username);
 
    echo $response;
  }

  // Insert user
  public function saveUserDetails(){
    $data = json_decode(file_get_contents("php://input"));

    $response = $this->Main_model->saveUserDetails($data);
 
    echo $response;
  }
}

5. Download AngularJS

  • Download AngularJS from its Official website.
  • Create assets directory in the project root directory.
  • Store the downloaded script in assets/ directory.

How to Get Records from Database with AngularJS in CodeIgniter


6. View

Create a user_view.php file in application/views/ directory.

Create a basic registration form and define ng-model directive on all textbox elements.

To check entered username is available or not define ng-keyup directive and display warning message using <span ng-show='isvalid' > when $scope.isvalid return true.

On the button define ng-click='saveUserDetails();'.

Script

Set the $scope.isvalid = false; to hide the warning message on the page load.

Create two functions –

  • checkUsename – Send $http request where pass the $scope.username and on successfully callback check response.data value if it is greater than 0 means username is not available and set $scope.isvalid = true otherwise set $scope.isvalid = false.
  • saveUserDetails – Get all model values and check all entered or not. If entered then check !$scope.isvalid returns false or not then send $http request to insert records in users table.

If the response is 1 then alert message and empty the field values.

Completed Code

<?php
defined('BASEPATH') OR exit('No direct script access allowed');
?><!DOCTYPE html>
<html lang="en">
<head>
  <script src='<?= base_url() ?>assets/angular.min.js'></script>
</head>
<body ng-app='myapp'>

  <div ng-controller='userCtrl'>
 
   <form name='form_reg'>
    <table>
     <tr>
      <td>Name : </td>
      <td><input type='text' name='name' ng-model='name'></td>
     </tr>
     <tr>
      <td>Username : </td>
      <td><input type='text' name='username' ng-model='username' ng-keyup='checUsername()'>
      <span style='color: red;' ng-show="isvalid">Username is not available!</span>
      </td>
     </tr>
     <tr>
      <td>Email : </td>
      <td><input type='text' name='email' ng-model='email'></td>
     </tr>
     <tr>
      <td>Password : </td>
      <td><input type='password' name='password' ng-model='password'></td>
     </tr>
     <tr>
      <td>&nbsp;</td>
      <td><input type='button' value='Submit' ng-click='saveUserDetails();'></td>
     </tr>
    </table>
   </form>
  </div>

 <!-- Script -->
<script>
var fetch = angular.module('myapp', []);
fetch.controller('userCtrl', ['$scope', '$http', function ($scope, $http) {
 
  $scope.isvalid = false;

  // Check username availability
  $scope.checUsername = function(){
 
   $http({
    method: 'post',
    url: '<?= base_url() ?>index.php/User/checkUsername',
    data: {username: $scope.username},
   }).then(function successCallback(response) {
 
    if(response.data > 0){
      $scope.isvalid = true;
    }else{
      $scope.isvalid = false;
    }

   });
  }

  // Save user
  $scope.saveUserDetails = function(){
   var name = $scope.name;
   var username = $scope.username;
   var email = $scope.email;
   var password = $scope.password;

   if(name !='' && username != '' && email != '' && password != ''){
 
     if(!$scope.isvalid){
       $http({
         method: 'post',
         url: '<?= base_url() ?>index.php/User/saveUserDetails',
         data: {name: name,username: username, email: email, password: password},
       }).then(function successCallback(response) {
 
         if(response.data == 1){
           $scope.name = "";
           $scope.username = "";
           $scope.email = "";
           $scope.password = "";
           alert('Save successfully');
         }
 
       });
      }
 
    }else{
       alert('Fill all details');
    }
 
   }
 
}]);

</script>

</body>
</html>

7. Demo

Enter the value in username textbox. Registered usernames – yssyogesh, sonarika, vishal, and sunil.

NOTE – This demo only checks username availability does not insert a record in the database.


8. Conclusion

If you also want to check the email id while input then performs the same steps as done for the username.

You can create separate methods in the controller and model for handling or use the same methods but update the code to handle both requests for the username and email element.

If you found this tutorial helpful then don't forget to share.

Leave a Comment