How to send AJAX request in CodeIgniter 3

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.

How to send AJAX request in CodeIgniter 3


Contents

  1. Table structure
  2. Model
  3. Controller
  4. View
  5. From External script
  6. Demo
  7. Conclusion

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 the users table where username = $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 and url helper.
  • index() – Get usernames by calling $this->Main_model->getUsernames() and assign in $users. Assign $users in $data['users']. Load user_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 in script/ 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

View 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.