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:
- Write the jquery script to make an ajax call.
- Create Routes.
- Build Controller function to handle ajax request.
- Display the response from the Controller.
1. Write the jquery script to make an ajax call.
ajax-request.php
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Document</title> <script src="https://code.jquery.com/jquery-3.6.0.min.js" integrity="sha256-/xUj+3OJU5yExlq6GSYGSHk7tPXikynS7ogEvDej/m4=" crossorigin="anonymous"></script> </head> <body> <div style=" margin: auto; width: 50%; padding: 10px;"> <button type="button" onclick="myFunction()">Click me</button> </div> <script> function myFunction(){ $.ajax({ url : '<?php echo site_url('/ajaxresponse')?>', type : 'POST', dataType: 'json', success: function(response){ alert(response); }, error: function(response){ alert(response); } }); } </script> </body> </html>
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.php
$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.
Home.php
<?php 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); } }
Useful links, One time temporary link for email verification
Published on Oct 19, 2021