CRUD Application Using CodeIgniter 4 and Vanilla JavaScript

CRUD Application Using CodeIgniter 4 and Vanilla JavaScript

In this tutorial you will learn how to build a Create-Read-Update-Delete (CRUD) application using CodeIgniter 4 and Vanilla Javascript..

Not only that,

I will also share with you how to use Bulma CSS for User Interface (UI) styles.

That way, the application is built to be more elegant, responsive, and user friendly.

Let's get started.

 

What is Vanilla JavaScript?

Vanilla Javascript is not a framework or library like Vue.js, JQuery, Angular, React, or something like that.

Instead, Vanilla Javascript is a joke that web developers term for Javascript.

In other words, Vanilla Javascript is Javascript.

Actually, to create applications built using jQuery can be done easily without jQuery.

Enough with just using JavaScript.

You can manipulate DOM (Document Object Models) without jQuery and you can also do AJAX Request without jQuery.

Cool right?

 

Step #1. Installing CodeIgniter 4

To install CodeIgniter 4, you can do it in 2 ways: manual installation and installation via composer.

In this tutorial, I will be using a manual installation.

Please download the CodeIgniter 4 file at the following link:

https://codeigniter.com

Then extract it on your web server.

If you are using WAMPSERVER, extract it in the folder:

C:/wamp64/www

If you are using XAMPP, extract it in the folder:

C:/xampp/htdocs

In this tutorial, I am using XAMPP.

Then rename to "crud" as shown below:

project-folder

Then, open the "crud" project folder using the code editor.                       

In this tutorial, I am using "Visual Studio Code".

If you also use Visual Studio Code it is better.

You can also use Sublime Text, PHP Storm, or any other code editor.

 

Step #2. Create a Database and Table

Create a new database on MySQL, you can use tools like SQLyog, PHPMyAdmin or similar tools.

Here I created a database with the name "crud_db".

If you create a database with the same name that's even better.

To create a database on MySQL, it can be done by executing the following query:

CREATE DATABASE crud_db;

The SQL command above will create a database with the name "crud_db".

Next, make a connection between the database and the CodeIgniter project.

Find the env file in the project root, then rename it to .env and open the file.

Then find the following code:

# database.default.hostname = localhost
# database.default.database = ci4
# database.default.username = root
# database.default.password = root
# database.default.DBDriver = MySQLi

Change it to be like the following:

database.default.hostname = localhost
database.default.database = crud_db
database.default.username = root
database.default.password = 
database.default.DBDriver = MySQLi

The next step is to create a table in the database "crud_db".

In this tutorial, I will be using the migration feature in CodeIgniter 4 for table creation.

Type the following command at the Terminal / Command Prompt:

php spark migrate:create product

Then Enter, then CodeIgniter will create a file with the initials "product" in the "app/Database/Migrations" folder..

Like the following picture:

migration

Open the file, then type the following code:

<?php namespace App\Database\Migrations;

use CodeIgniter\Database\Migration;

class Product extends Migration
{
    public function up()
    {
        //
        $this->forge->addField([
            'product_id'          => [
                    'type'           => 'INT',
                    'constraint'     => 5,
                    'unsigned'       => true,
                    'auto_increment' => true,
            ],
            'product_name'       => [
                    'type'           => 'VARCHAR',
                    'constraint'     => '100',
            ],
            'product_price' => [
                    'type'           => 'INT',
                    'constraint'     => 11,
            ],
        ]);
        $this->forge->addKey('product_id', true);
        $this->forge->createTable('product');
    }

    //--------------------------------------------------------------------

    public function down()
    {
        //
    }
}

In the code above, we only add the code to the function up().

Function up(), serves to create a table in the database with the specified fields.

In the above case, we create a table with the name "product" with fields product_id, product_name, and product_price along with the data type and other attributes.

If you are not familiar with migration, it might seem complicated, but it really isn't.

Next, type the following command at the Terminal / Command Prompt:

php spark migrate

Then Enter, then CodeIgniter will automatically create a "product" table with fields product_id, product_name, and product_price in the database "crud_db".

 

Step #3. Models

In this tutorial, only one model file is needed, namely "ProductModel.php".

Create a model file named "ProductModel.php" in the "app/Models" folder, then type the following code:

<?php namespace App\Models;

use CodeIgniter\Model;

class ProductModel extends Model
{
    protected $table = 'product';
    protected $primaryKey = 'product_id';
    protected $allowedFields = ['product_name','product_price'];
}

 

Step #4. Controllers

Create a controller file named "Product.php" in the "app/Controllers" folder, then type the following code:

<?php namespace App\Controllers;

use CodeIgniter\Controller;
use App\Models\ProductModel;

class Product extends Controller
{
    public function index()
    {
        // Call view "Product View"
        echo view('product_view');
    }

    // Get All Products
    public function getProduct()
    {
        $model = new ProductModel();
        $data = $model->findAll();
        return json_encode($data);
    }

    // Create product
    public function create(){
        $method = $this->request->getMethod(true);
        // Insert data to database if method "POST"
        if($method == 'POST'){
            $model = new ProductModel();
            $json = $this->request->getJSON();
            $data = [
                'product_name'  => $json->product_name,
                'product_price' => $json->product_price
            ];
            $model->insert($data);
        }else{
            // Call View "Add Product" if method "GET"
            echo view('add_product_view');
        } 
    }

    // Update product
    public function update($id = null){
        $method = $this->request->getMethod(true);
        $model = new ProductModel();
        // Insert data to database if method "PUT"
        if($method == 'PUT'){
            $json = $this->request->getJSON();
            $data = [
                'product_name' => $json->product_name,
                'product_price' => $json->product_price
            ];
            $model->update($id, $data);
        }else{
            // Call View "Edit Product" if method "GET"
            $data['data'] = $model->find($id);
            echo view('edit_product_view', $data);
        } 
    }

    // Delete product
    public function delete($id = null){
        $model = new ProductModel();
        $model->delete($id);
    }

}


Step #5. Create View file “product_view.php”

Create a view file named "product_view.php" in the "app/Views" folder, then type the following code:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Product List</title>
    <!-- Include Bulma CSS CDN -->
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bulma@0.9.1/css/bulma.min.css">
</head>
<body>
    
    <section class="section">
        <div class="container">
        <!-- Add New Product Button -->
        <a href="/product/create" class="button is-primary mb-3">Add New</a>
        <!-- Product List Table -->
        <table class="table is-bordered is-fullwidth">
            <thead>
                <tr>
                    <th>Product Name</th>
                    <th>Price</th>
                    <th>Actions</th>
                </tr>
            </thead>
            <tbody>
            
            </tbody>    
        </table>
        </div>
    </section>

    <script>
        document.addEventListener('DOMContentLoaded', () => {
            // Call function showData on loaded content
            showData();
        });

        // show data from database
        const showData = async () => {
            try {
                const response = await fetch('/product/getProduct', {
                    headers: {
                        "Content-Type": "application/json",
                        "X-Requested-With": "XMLHttpRequest"
                    }
                });
                const data = await response.json();
                
                const table = document.querySelector('table tbody');
                let rowData = "";
                data.forEach(({ product_id, product_name, product_price }) => {
                    rowData += `<tr>`;
                    rowData += `<td>${product_name}</td>`;
                    rowData += `<td>${product_price}</td>`;
                    rowData += `<td>`;
                    rowData += `<a href="/product/update/${product_id}" class="button is-info is-small">Edit</a>`;
                    rowData += `<a class="button is-danger is-small" data-id="${product_id}">Delete</a>`;
                    rowData += `</td>`;
                    rowData += `</tr>`;
                });
                table.innerHTML = rowData;
            } catch (err) {
                console.log(err);
            }
        }

        // Delete product method
        document.querySelector('table tbody').addEventListener('click', async (event) => {
            const id = event.target.dataset.id;
            try {
                await fetch(`/product/delete/${id}`, {
                    method: "DELETE",
                    headers: {
                        "Content-Type": "application/json",
                        "X-Requested-With": "XMLHttpRequest"
                    }
                }); 
                showData();
            } catch (err) {
                console.log(err);
            }
        });

    </script>
</body>
</html>

 

Step #6. Creat View file “add_product_view.php”

Create a View file again named "add_product_view.php" in the "app/Views" folder, then type the following code:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Add Product</title>
    <!-- Include Bulma CSS CDN -->
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bulma@0.9.1/css/bulma.min.css">
</head>
<body>
    <section class="section">
        <div class="container">
        <form>
            <div class="field">
                <label class="label">Product Name</label>
                <div class="control">
                    <input class="input" name="productName" type="text" placeholder="Product Name">
                </div>
            </div>

            <div class="field">
                <label class="label">Price</label>
                <div class="control">
                    <input class="input" name="productPrice" type="text" placeholder="Price">
                </div>
            </div>

            <div class="control">
                <button class="button is-primary">SAVE</button>
            </div>

        </form>
        </div>
    </section>
    <script>
        const form = document.querySelector('form');
        
        // save product to database 
        form.addEventListener('submit', async (e) => {
            e.preventDefault();

            const product_name = form.productName.value;
            const product_price = form.productPrice.value;

            try {
                await fetch('/product/create', {
                    method: "POST",
                    body: JSON.stringify({ product_name, product_price }),
                    headers: {
                        "Content-Type": "application/json",
                        "X-Requested-With": "XMLHttpRequest"
                    }
                }); 
                location.assign('/product');
            } catch (err) {
                console.log(err);
            }
        });
        
    </script>
</body>
</html>

 

Step #7. Create View file “edit_product_view.php”

Create another view file called "edit_product_view.php" in the "app/Views" folder, then type the following code:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Update Product</title>
    <!-- Include Bulma CSS CDN -->
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bulma@0.9.1/css/bulma.min.css">
</head>
<body>
    <section class="section">
        <div class="container">
        <form>
            <div class="field">
                <label class="label">Product Name</label>
                <div class="control">
                    <input class="input" name="productName" type="text" value="<?= esc($data['product_name'])?>" placeholder="Product Name">
                </div>
            </div>

            <div class="field">
                <label class="label">Price</label>
                <div class="control">
                    <input class="input" name="productPrice" type="text" value="<?= esc($data['product_price'])?>" placeholder="Price">
                </div>
            </div>

            <div class="control">
                <!-- Input Hidden ID -->
                <input type="hidden" name="productId" value="<?= esc($data['product_id'])?>">
                <button class="button is-primary">UPDATE</button>
            </div>

        </form>
        </div>
    </section>
    <script>
        const form = document.querySelector('form');

        // update product to database
        form.addEventListener('submit', async (e) => {
            e.preventDefault();

            const product_id = form.productId.value;
            const product_name = form.productName.value;
            const product_price = form.productPrice.value;

            try {
                await fetch(`/product/update/${product_id}`, {
                    method: "PUT",
                    body: JSON.stringify({ product_name, product_price }),
                    headers: {
                        "Content-Type": "application/json",
                        "X-Requested-With": "XMLHttpRequest"
                    }
                }); 
                location.assign('/product');
            } catch (err) {
                console.log(err);
            }
        });
        
    </script>
</body>
</html>

 

Step #8. Testing

To ensure whether the application that is built runs well, test it by typing the following command in the Terminal/Command Prompt:

php spark serve

Like the following picture:

php-serve

Next, open your browser and visit the following URL:

http://localhost:8080/product

If it goes well, it will look like this:

product-list

Click the "Add New" button, then the add new product form will appear as shown below:

add-product

Input the product name and price, then click the "SAVE" button.

If it goes well, it will look like the following image:

product-added

To edit data, click the "Edit" button, then a form to edit data will appear as shown below:

edit-product

Edit the product name or price, then click the "UPDATE" button to update the data.

If the update is successful, it will appear as shown below:

product-edited

To delete data, click the "Delete" button.

If the delete is successful, the data will disappear from the list.

product-list

 

Conclusion:

The discussion this time is how to create a CRUD (Create-Read-Update-Delete) application using CodeIgniter 4 and Vanilla Javascript.

Not only that, you have also learned how to use Bulma CSS for User Interface (UI) styles..

So what are you waiting for, Let's Coding!

Download Source Code

Share:



Sponsorship:


Recommended for you


Comments (0)

Leave a Comment