If you know how to send jQuery AJAX request in Core PHP then it is simpler for you to do it in CodeIgniter.
In CodeIgniter, you can use the controller and model to handle AJAX call instead of creating a separate file. Make AJAX call either from the view or external script file.
In this tutorial, I am creating a simple example to demonstrate the AJAX calling in CodeIgniter 3.
Contents
1. Table structure
I am using users
table in the example and added some records in the table.
CREATE TABLE `users` ( `id` int(11) NOT NULL PRIMARY KEY AUTO_INCREMENT, `username` varchar(80) NOT NULL, `name` varchar(80) NOT NULL, `email` varchar(80) NOT NULL );
2. Model
Navigate to application/models/
directory and create new Main_model.php
file.
Create 2 methods –
- getUsernames() – Fetch all usernames from the
users
table and return record in an Array format. - getUserDetails() – This method takes a single Array type parameter. If
$postData['username']
is set then fetch a record from theusers
table whereusername = $postData['username']
. Return record in an Array format.
Completed Code
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed'); class Main_model extends CI_Model { function getUsernames(){ $this->db->select('username'); $records = $this->db->get('users'); $users = $records->result_array(); return $users; } function getUserDetails($postData=array()){ $response = array(); if(isset($postData['username']) ){ // Select record $this->db->select('*'); $this->db->where('username', $postData['username']); $records = $this->db->get('users'); $response = $records->result_array(); } return $response; } }
3. Controller
Navigate to application/controllers/
directory and create a User.php
file.
Create the following methods –
- __consturct – Load
Main_model
model andurl
helper. - index() – Get usernames by calling
$this->Main_model->getUsernames()
and assign in$users
. Assign$users
in$data['users']
. Loaduser_view
view and pass$data
. - userDetails() – Using this method handle AJAX request.
Read POST value from AJAX call and get user details by calling getUserDetails()
method. Assign return response in $data
and return in JSON format.
Completed Code
<?php defined('BASEPATH') OR exit('No direct script access allowed'); class User extends CI_Controller { public function __construct(){ parent::__construct(); // Load Model $this->load->model('Main_model'); // Load base_url $this->load->helper('url'); } public function index(){ $users = $this->Main_model->getUsernames(); $data['users'] = $users; $this->load->view('user_view',$data); } public function userDetails(){ // POST data $postData = $this->input->post(); // get data $data = $this->Main_model->getUserDetails($postData); echo json_encode($data); } }
4. View
Navigate to application/views/
directory and create a user_view.php
file.
Create a <select id='sel_user'>
element and add <option >
by looping on $users
Array. Created <span >
elements to display selected username data.
Send AJAX request when change
event triggers on <select >
element.
In the AJAX POST request do the following –
- Send a request to the controller method
<?=base_url()?>index.php/User/userDetails
. - Pass selected dropdown value as
data
. - Set
dataType: 'json'
to handle JSON response. - On successfully callback read response values and set data to
<span>
elements.
Completed Code
<!doctype html> <html> <head> <title>How to send AJAX request in Codeigniter 3</title> </head> <body> Select Username : <select id='sel_user'> <?php foreach($users as $user){ echo "<option value='".$user['username']."' >".$user['username']."</option>"; } ?> </select> <!-- User details --> <div > Username : <span id='suname'></span><br/> Name : <span id='sname'></span><br/> Email : <span id='semail'></span><br/> </div> <!-- Script --> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.3/jquery.min.js"></script> <script type='text/javascript'> $(document).ready(function(){ $('#sel_user').change(function(){ var username = $(this).val(); $.ajax({ url:'<?=base_url()?>index.php/User/userDetails', method: 'post', data: {username: username}, dataType: 'json', success: function(response){ var len = response.length; $('#suname,#sname,#semail').text(''); if(len > 0){ // Read values var uname = response[0].username; var name = response[0].name; var email = response[0].email; $('#suname').text(uname); $('#sname').text(name); $('#semail').text(email); } } }); }); }); </script> </body> </html>
5. From External script
If you want to send AJAX request from external script file instead directly from view as the above example then you need little modify your view and script code.
user_view.php
- Include script file
Load external script file in view <script src='<?php echo base_url(); ?>script/script.js' type='text/javascript' ></script>
- base_url
Create a JavaScript variable var baseURL= "<?php echo base_url();?>";
that use in AJAX call.
<script src='<?php echo base_url(); ?>script/script.js' type='text/javascript' ></script> <script type='text/javascript'> var baseURL= "<?php echo base_url();?>"; </script>
Create script.js –
- Navigate to your project root and create a
script
folder. - Create
script.js
inscript/
folder.
Completed Code
$(document).ready(function(){ $('#sel_user').change(function(){ var username = $(this).val(); $.ajax({ url:baseURL+'index.php/user/userDetails', method: 'post', data: {username: username}, dataType: 'json', success: function(response){ var len = response.length; $('#suname,#sname,#semail').text(''); if(len > 0){ // Read values var uname = response[0].username; var name = response[0].name; var email = response[0].email; $('#suname').text(uname); $('#sname').text(name); $('#semail').text(email); } } }); }); });
6. Demo
7. Conclusion
In this tutorial, I showed how can you make AJAX call from view and external script file. You need to modify your external script and view file code to enable AJAX calls.
You can view this tutorial if you want to how to send AJAX request with a CSRF token.
If you found this tutorial helpful then don't forget to share.
Does this good code work even if the config parameters are set to true like this in config file:
$config[‘csrf_protection’] = TRUE;
$config[‘csrf_regenerate’] = TRUE;
most of the times ajax post don’t work except if you deal with the tokens. this is what i know, but how to do this ?? it’s a mistery.
if you know hox to add token management to avoid for each post to have a 403 error I would really love to know how you do.
Thanks a lot.
Thank Yogesh Singh, Great tutorial.
thank you, this is exactly what i’m looking for.
hello yogesh awesome work
can you help me out in a little issue ? as you are returning only one value from the database you are comparing the values in where clause , i want to use order-by and return all the values in ascending order or descending order , how can i do that ??? i guess i have to alter the javascript code part
thanks
Hellow ,
In your controller function , please update the code as given below
// POST data
$postData = $this->input->post(‘username’);
not working in my project
Hi, do I need to import my own users, seems not working
Please help
In your AJAX call, you have a `success` function, should you also have a `error` function in case something bad happens in userDetails() function (in User.php)? This could be useful in debugging
not working for me is return to me ‘undefined’ values
your code is ok, i copy your code in my project as per your code run ok, this code use in my project not response json object , why ?
Sir, i used this code in my project. There is problem in response In daratype json error , if I put dataType text then response works , how to get response in json dataType
Sir, can I implement this code with the Select2 javascript? I was newbie about programing and I try to implement your code into my project and I Failed. Please Help Me to make this code run in Select2.
How do I create a filter based on three drop-downs, not one
Please I am waiting for you to answer as soon as possible