Get Data from Database using AJAX in Codeigniter 4

Get Data from Database using AJAX in Codeigniter 4

To get data from database using ajax jquery in codeIgniter 4; In this tutorial guide, you will learn how to fetch or get data from database using jquery ajax in codeIgniter 4 projects.

Codeigniter 4 Get Data from Database Using Ajax jQuery

Using the following steps, you can fetch or get data from database in codeigniter 4 and display in table using jQuery Ajax:

  • Step 1: Setup Codeigniter Project
  • Step 2: Basic Configurations
  • Step 3: Create a Database and Tables
  • Step 4: Setup Database Credentials
  • Step 5: Create Model and Controller
  • Step 6: Create a Views
  • Step 7: Start Development server

Step 1: Setup Codeigniter Project

In this step, you need to download the latest version of Codeigniter 4, Go to this link https://codeigniter.com/download and Download Codeigniter 4 fresh new setup and unzip the setup in your local system xampp/htdocs/ . And change the download folder name “demo”

Step 2: Basic Configurations

Next step, you need to set some basic configuration on the app/config/app.php file, so let’s visit application/config/config.php and open this file on the text editor.

Then Set Base URL like this

public $baseURL = 'http://localhost:8080';
To
public $baseURL = 'http://localhost/demo/';

Step 3: Create a Database and Tables

Once you have setup basic configuration. Now, you need to create a database name demo, so let’s open your PHPMyAdmin and create the database with the name demo.

So, you can use the below SQL query for creating a table in your database.

CREATE TABLE users (
    id int(11) NOT NULL AUTO_INCREMENT COMMENT 'Primary Key',
    name varchar(100) NOT NULL COMMENT 'Name',
    email varchar(255) NOT NULL COMMENT 'Email Address',
    PRIMARY KEY (id)
  ) ENGINE=InnoDB DEFAULT CHARSET=latin1 COMMENT='datatable demo table' AUTO_INCREMENT=1;
  
INSERT INTO `users` (`id`, `name`, `email`) VALUES
(1, 'John Doe', '[email protected]'),
(2, 'Vanya Hargreeves', '[email protected]'),
(3, 'Luther Hargreeves', '[email protected]'),
(4, 'Diego Hargreeves', '[email protected]'),
(5, 'Klaus Hargreeves', '[email protected]'),
(6, 'Ben Hargreeves', '[email protected]'),
(7, 'The Handler', '[email protected]');

Step 4: Setup Database Credentials

Once you have created database for your ci projects. Now, you need to connect to your created database with ci projects.

So, you need to visit app/Config/Database.php and open database.php file in text editor. After opening the file in a text editor, Then set up database credentials in this file like below.

	public $default = [
		'DSN'      => '',
		'hostname' => 'localhost',
		'username' => 'root',
		'password' => '',
		'database' => 'demo',
		'DBDriver' => 'MySQLi',
		'DBPrefix' => '',
		'pConnect' => false,
		'DBDebug'  => (ENVIRONMENT !== 'production'),
		'cacheOn'  => false,
		'cacheDir' => '',
		'charset'  => 'utf8',
		'DBCollat' => 'utf8_general_ci',
		'swapPre'  => '',
		'encrypt'  => false,
		'compress' => false,
		'strictOn' => false,
		'failover' => [],
		'port'     => 3306,
	];

Step 5: Create Model and Controller

In this steps, you need to create one model and controller file in your ci projects.

So go to app/Models/ and create here one model. And then you need to create one model name userModel.php and update the following code into your userModel.php file:

<?php 
namespace App\Models;
use CodeIgniter\Model;
 
class UserModel extends Model
{
    protected $table = 'users';
    protected $allowedFields = ['name', 'email'];
    public function getUsers($id = false) {
      if($id === false) {
        return $this->findAll();
      } else {
          return $this->getWhere(['id' => $id]);
      }
    }
    
}
?>

Next, Go to app/Controllers and create a controller name AjaxController.php. In this controller, you need to create some method/function. As follows:

<?php 
namespace App\Controllers; 
use CodeIgniter\Controller;
use App\Models\UserModel;
 
class AjaxController extends BaseController {
 
    public function index(){
		$data['name'] = 'Mac Shine';
		$data['content'] = 'list/index';
        return view('templates/main', $data);
    }
    public function user_table(){
        $model = new UserModel();
		$data['users'] = $model->getUsers();
        echo view('list/user_table', $data);
    }
}
?>

Next, Open app/Config/Routes.php file and define the following route inside it:

$routes->get('/', 'AjaxController::index');
$routes->match(['get', 'post'], 'AjaxController/user_table', 'AjaxController::user_table');

Step 6: Create a Views

Now you need to create app/Views/templates/main.php file and add the following code into it:

<!doctype html>
<html lang="en">
<head>
  <!-- Required meta tags -->
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
  <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css">
  <script src="https://code.jquery.com/jquery-3.5.1.min.js"></script>
  <title>Codeigniter AJAX Fetch Data from Database Example - Tutsmake.com</title>
</head>
<body>
  <?php echo view($content); ?>
</body>
</html>

Once you have created main.php file. Now you need to create list/index.php, go to the application/views/list folder and create the index.php file. and update the following HTML into your files:

<div id="userTable"> </div>
<script>
    reloadTable()
    function reloadTable() {
      $.ajax({
        url: "<?php echo site_url(); ?>/AjaxController/user_table",
        beforeSend: function (f) {
          $('#userTable').html('Load Table ...');
        },
        success: function (data) {
          $('#userTable').html(data);
        }
      })
    }
</script>

Then, create app/Views/list/user_table.php file and insert the given below code in it.

<table class="table">
    <thead>
      <tr>
        <th>Id</th>
        <th>Name</th>
        <th>Email</th>
      </tr>
    </thead>
    <tbody>
      <?php foreach($users as $data) {  ?>
      <tr>
        <td><?php echo $data['id']; ?></td>
        <td><?php echo $data['name']; ?></td>
        <td><?php echo $data['email']; ?></td>
      </tr>
      <?php } ?>
    </tbody>
  </table>

Step 7: Start Development server

Now, open your terminal or cmd and execute the following command into it to start the development server:

php spark serve

To start the development server, Go to the browser and hit below the URL.

http://localhost:8080

Conclusion

That’s all; In this tutorial guide, you have learned how to fetch or get data from a database and display in table using jquery Ajax in codeIgniter 4 projects.

Recommended Codeigniter Posts

If you have any questions or thoughts to share, use the comment form below to reach us.

AuthorAdmin

My name is Devendra Dode. I am a full-stack developer, entrepreneur, and owner of Tutsmake.com. I like writing tutorials and tips that can help other developers. I share tutorials of PHP, Python, Javascript, JQuery, Laravel, Livewire, Codeigniter, Node JS, Express JS, Vue JS, Angular JS, React Js, MySQL, MongoDB, REST APIs, Windows, Xampp, Linux, Ubuntu, Amazon AWS, Composer, SEO, WordPress, SSL and Bootstrap from a starting stage. As well as demo example.

Leave a Reply

Your email address will not be published. Required fields are marked *