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>

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.

Related Post

Spread the love

Be First to Comment

Leave a Reply

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