How to send AJAX request in CodeIgniter

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

How to Send AJAX Request In CodeIgniter


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.

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
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

2. Model

Navigate to application/models/ directory and create new Main_model.php file.

Create a getUserDetails() method to fetch POST username user detail from users table and return an Array to the controller.

Completed Code

<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');

class Main_model extends CI_Model {

  function getUserDetails($postData){
 
    $response = array();
 
    if($postData['username'] ){
 
      // Select record
      $this->db->select('*');
      $this->db->where('username', $postData['username']);
      $q = $this->db->get('users');
      $response = $q->result_array();
 
    }
 
    return $response;
  }

}

3. Controller

Navigate to application/controllers/ directory and create a User.php file.

Create two methods index() and userDetails().

  • index() – Load user_view and
  • userDetails() – Read POST value from AJAX call and load Main_model to get user details by calling getUserDetails() method. Return the result as response.

Completed Code

<?php
defined('BASEPATH') OR exit('No direct script access allowed');

class User extends CI_Controller {

 public function index(){

  // load base_url
  $this->load->helper('url');

  // load view
  $this->load->view('user_view');
 }

 public function userDetails(){
  // POST data
  $postData = $this->input->post();

  //load model
  $this->load->model('Main_model');

  // 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 drop-down list and send AJAX request when change event triggers.

Within AJAX call do the following –

  • Send 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 HTML elements.

Completed Code

<!doctype html>
<html>
 <head>
   <title>How to send AJAX request in Codeigniter</title>
 </head>
 <body>
 
  Select Username : <select id='sel_user'>
   <option value='yssyogesh'>yssyogesh</option>
   <option value='sonarika'>sonarika</option>
   <option value='vishal'>vishal</option>
   <option value='sunil'>sunil</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.2.1/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;

      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);
 
      }else{
       $('#suname').text('');
       $('#sname').text('');
       $('#semail').text('');
      }
 
     }
   });
  });
 });
 </script>
 </body>
</html>

5. From External script

If you want to send AJAX request from external script file instead directly from view as 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 directory and create a script directory.
  • Create script.js in script/ directory.

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;

    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);
 
    }else{
     $('#suname').text('');
     $('#sname').text('');
     $('#semail').text('');
    }
 
   }
  });
 });
});

6. Demo

Select username from the dropdown.


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

If you found this tutorial helpful then don't forget to share.

Related Post

Spread the love
  • 1
  •  
  •  
  •  
  •  
  •  

8 Comments

  1. Edwin said:

    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.

    March 17, 2018
    Reply
  2. tahraka said:

    Thank Yogesh Singh, Great tutorial.

    July 28, 2018
    Reply
  3. justincool said:

    thank you, this is exactly what i’m looking for.

    August 25, 2018
    Reply
  4. Usman Ahmed said:

    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

    October 12, 2018
    Reply
    • Yogesh Singh said:

      Hi Usman,
      You need to modify the Model code. Just add order_by in $this->db and pass column name and order type ( asc or desc ).

      Here, is the example –
      $this->db->select(‘*’);
      $this->db->where(‘username’, $postData[‘username’]);
      $this->db->order_by(“id”, “asc”);
      $q = $this->db->get(‘users’);
      $response = $q->result_array();

      October 12, 2018
      Reply
  5. Leon Dev said:

    Hellow ,
    In your controller function , please update the code as given below
    // POST data
    $postData = $this->input->post(‘username’);

    October 17, 2018
    Reply
    • Yogesh Singh said:

      Hi Leon,
      Thanks, for your suggestion but the tutorial code is also correct where I am directly passing POST value to model and read it.

      October 17, 2018
      Reply

Leave a Reply

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