CodeIgniter Ajax Signup with Validation using jQuery

Installing CodeIgniter

If you don't have CodeIgniter installed yet, you can use this link to download the latest version of CodeIgniter which is 3.1.7 that I've used in this tutorial. After downloading, extract the file in the folder of your server. Since I'm using XAMPP as my localhost server, I've put the folder in htdocs folder of my XAMPP. Then, you can test whether you have successfully installed codeigniter by typing your app name in your browser. In my case, I named my app as codeigniter_register_ajax so I'm using the below code.
  1. localhost/codeigniter_register_ajax
codeigniter successful install

Creating our Database

First we are going to create our database. 1. Open your phpMyAdmin. 2. Create a new database named codeigniter. 3. Click the database that we created, click SQL tab then paste the below code or import the included .sql file in the downloadable of this source code located in db folder.
  1. CREATE TABLE `users` (
  2. `email` varchar(40) NOT NULL,
  3. `password` varchar(40) NOT NULL,
  4. `fname` varchar(100) NOT NULL,

Connecting our App into our Database

Next, we're going to connect our codeigniter application to the database that we created earlier. 1. In your codeigniter app folder, open database.php located in application/config folder. 2. Update database.php with your credential the same as what I did in the image below. database is where we define the database that we created earlier. database configuration codeigniter

Configuring our Base URL

Next, we configure our base url to tell codeigniter that this is the URL of our site/application. We're gonna be using this a lot that's why we need to configure this. 1. In your codeigniter app folder, open config.php located in application/config folder. 2. Find and edit the ff line:
  1. $config['base_url'] = 'http://localhost/codeigniter_register_ajax';
where codeigniter_register_ajax is the name of your app folder.

Creating our Model

Next, we create the model for our app. Take note that the first letter of your model name should be in CAPITAL letter and the name of the model should be the same as the file name to avoid confusion. Create a file named Users_model.php in application/models folder of our app and put the ff codes.
  1. <?php
  2. class Users_model extends CI_Model {
  3. function __construct(){
  4. parent::__construct();
  5. $this->load->database();
  6. }
  7.  
  8. public function getAllUsers(){
  9. $query = $this->db->get('users');
  10. return $query->result();
  11. }
  12.  
  13. public function register($user){
  14. return $this->db->insert('users', $user);
  15. }
  16.  
  17. }
  18. ?>

Creating our Controller

Next step is to create our controller. Controllers follow the same naming convention as models. Create a file named User.php in application/controllers folder of our app and put the ff codes.
  1. <?php
  2. defined('BASEPATH') OR exit('No direct script access allowed');
  3.  
  4. class User extends CI_Controller {
  5.  
  6. function __construct(){
  7. parent::__construct();
  8. $this->load->model('users_model');
  9. // load form and url helpers
  10. $this->load->helper(array('form', 'url'));
  11. // load form_validation library
  12. $this->load->library('form_validation');
  13. }
  14.  
  15. public function index(){
  16. $this->load->view('register_form');
  17. }
  18.  
  19. public function fetch(){
  20. $data = $this->users_model->getAllUsers();
  21. foreach($data as $row){
  22. ?>
  23. <tr>
  24. <td><?php echo $row->id; ?></td>
  25. <td><?php echo $row->email; ?></td>
  26. <td><?php echo $row->password; ?></td>
  27. <td><?php echo $row->fname; ?></td>
  28. </tr>
  29. <?php
  30. }
  31. }
  32.  
  33. public function register(){
  34. $output = array('error' => false);
  35.  
  36. /* Set validation rule for name field in the form */
  37. $this->form_validation->set_rules('email', 'Email', 'valid_email|required');
  38. $this->form_validation->set_rules('password', 'Password', 'required|min_length[7]|max_length[30]');
  39. $this->form_validation->set_rules('fname', 'Full Name', 'required');
  40.  
  41. if ($this->form_validation->run() == FALSE) {
  42. $output['error'] = true;
  43. $output['message'] = validation_errors();
  44. }
  45. else {
  46. $user['email'] = $_POST['email'];
  47. $user['password'] = $_POST['password'];
  48. $user['fname'] = $_POST['fname'];
  49.  
  50. $query = $this->users_model->register($user);
  51.  
  52. if($query){
  53. $output['message'] = 'User registered successfully';
  54. }
  55. else{
  56. $output['error'] = true;
  57. $output['message'] = 'User registered successfully';
  58. }
  59. }
  60.  
  61. echo json_encode($output);
  62. }
  63.  
  64. }

Defining our Default Controller

Next, we are going to set our default controller so that if no controller is defined, this default controller will be used. Open routes.php located in application/config folder and set the default route to our user controller.
  1. $route['default_controller'] = 'user';

Creating our Views

Lastly, we create the views of our app. Create the ff files inside application/views folder. register_form.php
  1. <!DOCTYPE html>
  2. <html>
  3. <head>
  4. <meta charset="utf-8">
  5. <title>CodeIgniter Ajax Signup with Validation</title>
  6. <link rel="stylesheet" type="text/css" href="<?php echo base_url(); ?>bootstrap/css/bootstrap.min.css">
  7. <script src="<?php echo base_url(); ?>jquery/jquery.min.js"></script>
  8. <script src="<?php echo base_url(); ?>bootstrap/js/bootstrap.min.js"></script>
  9. </head>
  10. <body>
  11. <div class="container">
  12. <h1 class="page-header text-center">CodeIgniter Ajax Signup with Validation</h1>
  13. <div class="row">
  14. <div class="col-sm-4">
  15. <div class="login-panel panel panel-primary">
  16. <div class="panel-heading">
  17. <h3 class="panel-title"><span class="glyphicon glyphicon-user"></span> Register
  18. </h3>
  19. </div>
  20. <div class="panel-body">
  21. <form id="regForm">
  22. <fieldset>
  23. <div class="form-group">
  24. <input class="form-control" placeholder="Email" type="text" name="email">
  25. </div>
  26. <div class="form-group">
  27. <input class="form-control" placeholder="Password" type="password" name="password">
  28. </div>
  29. <div class="form-group">
  30. <input class="form-control" placeholder="Full Name" type="text" name="fname">
  31. </div>
  32. <button type="submit" class="btn btn-lg btn-primary btn-block">Sign Up</button>
  33. </fieldset>
  34. </form>
  35. </div>
  36. </div>
  37. <div id="responseDiv" class="alert text-center" style="margin-top:20px; display:none;">
  38. <button type="button" class="close" id="clearMsg"><span aria-hidden="true">&times;</span></button>
  39. <span id="message"></span>
  40. </div>
  41. </div>
  42. <div class="col-sm-8">
  43. <table class="table table-bordered table-striped">
  44. <thead>
  45. <tr>
  46. <th>ID</th>
  47. <th>Email</th>
  48. <th>Password</th>
  49. <th>FullName</th>
  50. </tr>
  51. </thead>
  52. <tbody id="tbody">
  53. </tbody>
  54. </table>
  55. </div>
  56. </div>
  57. </div>
  58. <script type="text/javascript">
  59. $(document).ready(function(){
  60. getTable();
  61.  
  62. $('#regForm').submit(function(e){
  63. e.preventDefault();
  64. var url = '<?php echo base_url(); ?>';
  65. var reg = $('#regForm').serialize();
  66. $.ajax({
  67. type: 'POST',
  68. data: reg,
  69. dataType: 'json',
  70. url: url + 'index.php/user/register',
  71. success:function(response){
  72. $('#message').html(response.message);
  73. if(response.error){
  74. $('#responseDiv').removeClass('alert-success').addClass('alert-danger').show();
  75. }
  76. else{
  77. $('#responseDiv').removeClass('alert-danger').addClass('alert-success').show();
  78. $('#regForm')[0].reset();
  79. getTable();
  80. }
  81. }
  82. });
  83. });
  84.  
  85. $(document).on('click', '#clearMsg', function(){
  86. $('#responseDiv').hide();
  87. });
  88.  
  89. });
  90. function getTable(){
  91. var url = '<?php echo base_url(); ?>';
  92. $.ajax({
  93. type: 'POST',
  94. url: url + 'index.php/user/fetch',
  95. success:function(response){
  96. $('#tbody').html(response);
  97. }
  98. });
  99. }
  100. </script>
  101. </body>
  102. </html>
That ends this tutorial. Happy Coding :)

Add new comment