CodeIgniter 4 AJAX Tutorial
About Lesson

Creating a simple tutorial on signup with AJAX using CodeIgniter 4 involves several steps, including setting up the database, creating the controller, model, and view, and implementing AJAX for asynchronous communication. Here’s a step-by-step guide:

 

Step 1: Setup CodeIgniter 4 Project

Make sure you have CodeIgniter 4 installed. If not, you can follow the official documentation to install it.

 

Step 2: Database Configuration

Configure your database settings in App/Config/Database.php.

public array $default = [
'DSN' => '',
'hostname' => 'localhost',
'username' => 'root',
'password' => '',
'database' => 'infovistar_ci4_db',
'DBDriver' => 'MySQLi',
'DBPrefix' => '',
'pConnect' => false,
'DBDebug' => true,
'charset' => 'utf8',
'DBCollat' => 'utf8_general_ci',
'swapPre' => '',
'encrypt' => false,
'compress' => false,
'strictOn' => false,
'failover' => [],
'port' => 3306,
'numberNative' => false,
];

 

Step 3: Create Database Table

Create a table for users in your database.

CREATE TABLE `login_info` (
  `id` int(10) NOT NULL,
  `name` varchar(255) NOT NULL,
  `email` varchar(255) NOT NULL,
  `password` varchar(255) NOT NULL,
  `mobile_number` varchar(50) NOT NULL,
  `ip_address` varchar(255) NOT NULL,
  `created_at` datetime NOT NULL,
  `updated_at` timestamp NOT NULL DEFAULT current_timestamp() ON UPDATE current_timestamp(),
  `status` varchar(10) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_general_ci;

ALTER TABLE `login_info`
  ADD PRIMARY KEY (`id`);

 

Step 4: Model

Create a model to interact with the database.

<?php
namespace App\Models\login;

use CodeIgniter\Model;
use CodeIgniter\Database\ConnectionInterface;

class LoginModel extends Model {

protected $db;
public function __construct(ConnectionInterface &$db) {
$this->db =& $db;

$this->table = 'login_info';
}

public function addEntry($data) {
$this->db
->table($this->table)
->insert($data);
return $this->db->insertID();
}

public function updateEntry($where, $data) {
return $this->db
->table($this->table)
->where($where)
->set($data)
->update();
}

public function deleteEntry($where) {
return $this->db
->table($this->table)
->where($where)
->delete();
}

public function getEntry($where) {
return $this->db
->table($this->table)
->where($where)
->get()
->getRow();

}

public function getEntryList($where = 0) {
if($where) {
return $this->db
->table($this->table)
->where($where)
->get()
->getResult();
} else {
return $this->db
->table($this->table)
->get()
->getResult();
}
}

public function getNumRows($where) {
return $this->db
->table($this->table)
->where($where)
->get()
->getNumRows();

}
}

 

Step 5: Controller

Create a controller for handling signup requests.

<?php
namespace App\Controllers\signup;

use App\Controllers\BaseController;

use App\Models\login\LoginModel;

class Signup extends BaseController {

public function __construct() {
$db = db_connect();
$this->login = new LoginModel($db);

$this->ip_address = $_SERVER['REMOTE_ADDR'];
$this->datetime = date("Y-m-d H:i:s");

}

public function index() {
$this->signup();
}

public function signup() {
$data = [];
$data ['content_title'] = 'Sign Up';
echo view('signup/signup', $data);
}

public function create() {
$name = $this->request->getPost('name');
$email = $this->request->getPost('email');
$password = $this->request->getPost('password');
$mobile_number = $this->request->getPost('mobile_number');

$where = [
'email' => $email,
];
$has_account = $this->login->getEntry($where);
if($has_account) {
$json = [
'status' => false,
'message' => showDangerMessage("Entered email address is already registered"),
];
} else {
$data = [
'name' => $name,
'email' => $email,
'password' => md5($password),
'mobile_number' => $mobile_number,
'ip_address' => $this->ip_address,
'created_at' => $this->datetime,
'status' => "1",
];
$result = $this->login->addEntry($data);
if($result) {
$json = [
'status' => true,
'message' => showSuccessMessage("Your account has been created successfully"),
'location' => base_url('login'),
];
} else {
$json = [
'status' => false,
'message' => showDangerMessage("Something went wrong. Please try again!"),
];
}
}
echo json_encode($json);
}
}

 

Step 6: View

Create a view for the signup form.

<!DOCTYPE html>
<html lang="en">

<head>
<title><?php echo $content_title; ?></title>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@4.6.2/dist/css/bootstrap.min.css">
<script src="https://cdn.jsdelivr.net/npm/jquery@3.7.1/dist/jquery.slim.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/popper.js@1.16.1/dist/umd/popper.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/bootstrap@4.6.2/dist/js/bootstrap.bundle.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.7.1/jquery.min.js"></script>
</head>

<body>
<div class="jumbotron text-center">
<h1>Welcome to Infovistar.in</h1>
<p>Registration Example with AJAX</p>
</div>
<div class="container">
<div class="row">
<div class="col-sm-3">

</div>
<div class="col-sm-6">
<div class="message"></div>
<form id="form-signup" method="post" autocomplete="off">
<div class="form-group">
<label>Name</label>
<input type="text" class="form-control" id="name" name="name" placeholder="Name" required>
</div>
<div class="form-group">
<label>Email</label>
<input type="email" class="form-control" id="email" name="email" placeholder="Email" required>
</div>
<div class="form-group">
<label>Password</label>
<input type="password" class="form-control" id="password" name="password" placeholder="Password" required>
</div>
<div class="form-group">
<label>Mobile No.</label>
<input type="text" class="form-control" id="mobile_number" name="mobile_number" placeholder="Mobile No." maxlength="10" required>
</div>
<div class="form-group">
<button type="submit" id="btn-signup" class="btn btn-success">Create Account</button>
<a href="<?php echo base_url("login"); ?>" class="btn btn-info">Go to Login</a>
</div>
</form>
</div>
</div>
</div>

<script>
$(document).ready(function() {
$("#form-signup").on("submit", function(e) {
e.preventDefault();
let data = $(this).serialize();
$.post('<?php echo base_url("signup/create"); ?>', data, function(result) {
$(".message").html(result.message);
if(result.status) {
// window.location.replace(result.location);
}
}, 'json');
});
});
</script>
</body>

</html>

 

Step 7: Routes

Configure a route to access the signup page and handle the signup request.

 
// New Account Routes
$routes->group('signup', function($routes) {
$routes->get('/', 'signup\Signup::index');
$routes->post('create', 'signup\Signup::create');
});

 

Step 8: Test

Run in command prompt: php spark serve

Visit http://localhost:8080/signup in your browser and test the signup form.