Dj Techblog

A blog on web development

Ajax call to controller function in Codeigniter-4

Last modified on Oct 19, 2021

Ajax reuest to Controller function in Codeigniter 4 makes the site more fast and responsive. Let's see how can we make an ajax request to controller function and how the function responds to every ajax request.

The complete process can be divided into following steps:

  1. Write the jquery script to make an ajax call.
  2. Create Routes.
  3. Build Controller function to handle ajax request.
  4. Display the response from the Controller.

1. Write the jquery script to make an ajax call.


<!DOCTYPE html>
<html lang="en">
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <script src="" integrity="sha256-/xUj+3OJU5yExlq6GSYGSHk7tPXikynS7ogEvDej/m4=" crossorigin="anonymous"></script>
            <div style="  margin: auto;
                        width: 50%;
                        padding: 10px;">
                  <button type="button" onclick="myFunction()">Click me</button>  
                function myFunction(){
                    url : '<?php echo site_url('/ajaxresponse')?>',
                    type : 'POST',
                    dataType: 'json',
                    success: function(response){
                    error: function(response){

There is a button, clicking on the button will make an ajax request to Controller function. The Controller function will handle the request and will serve appropriate response, which will will be displayed on the site as a alert message.

2. Create Routes.


    $routes->get('/ajax-request', 'Home::ajaxrequest');
    $routes->match(['get', 'post'], '/ajaxresponse', 'Home::ajaxresponse');

It's necessary to add Routes for your every ajax request to Controller function.

3. Build Controller function to handle ajax request.



namespace App\Controllers;
use CodeIgniter\Controller;

class Home extends BaseController
    function ajaxrequest(){
        echo view('ajax-request');
    function ajaxresponse(){
        $output="Ajax request Success.";
        echo json_encode($output);

Published on Oct 19, 2021

Ad section


Debabratta Jena

I mainly write about HTML5, CSS3, Javascript, Angular JS, Ajax, PHP, Mysql, On page SEO, Google Ads, Tag manager, Universal Analytics, Google My Business, SERP, Apache server configuration etc, Yoga is my passion.

Reach to me in the contact us form below

Follow me on

Contact us



Php HTML5 Javascript CSS Ajax Angular JS Google My bisiness Listing Google tag Manager Google Universal Analytics Search Engine Optimization On page SEO Off page SEO Google Marketing platform Digital Marketing Google Ads Mysql Apache Server

Ad section

Subscribe to get email notification about our new post



We neither sell nor share your personal information with any third party. Your identity is safe with us.