Amitav Roy

Blog on web and travel

Ajax data using Angular JS http and use $route service inside Codeigniter framework

Posted on July 2019

Angular JS and Codeigniter

This is my second tutorial on Angular JS. In this tutorial I will show you how to get ajax data using Angular JS http service and how to use $route service – a very powerful and sleek feature where you can define multiple pages inside a single page, load different content without refreshing the page. Similar to how in gmail we can look at different mails without refreshing the page.

This is going to be a big tutorial as I am covering quite a few things so let me lay down where I am going to start from and what are the things that we are going to do in this tutorial.

The code which I will be writing is a continuation of my last tutorial. So, if you want to use something as a starting point, check this tutorial: Single page app Angular JS $http inside Code Igniter using Twitter Bootstrap and you will find the code at the bottom.

Here are the core things that we will be doing in Angular JS

  1. Define a module in Angular JS
  2. User $route service for deep linking
  3. Get ajax data using Angular JS $http service

To start with I have created a new module inside my Codeigniter application/modules folder called demo2. This is a fresh set of code as the last article is inside demo1 folder.

The controller

The controller has the index function which is kind of the main place holder page inside which we will use the deep linking angular js service. For example for me the urls are like:

http://localhost/tutorials/demo2#/view1 and http://localhost/tutorials/demo2#/view2.

Here demo2 uses the index function and then the rest is done using Angular JS juice. I also have view1 and view2 functions which works as partials which I will explain you in some time. And the last function is select_entries which returns a json formatter text.

class Demo2 extends CI_Controller {
  function __construct() {
    parent::__construct();
  }
  
  function index() {
    $data['pagetitle'] = 'Demo page for Angular JS';
    $data['viewname'] = 'index_v';
    $data['scripts']['demo2'] = 'demo2';
  
    $this->load->view('master',$data);
  }
  
  function view1() {
    $this->load->view('demo2/partial_one');
  }
  
  function view2() {
    $this->load->view('demo2/partial_two');
  }
  
  function select_entries() {
    // Checking if post data is available
    if (isset($_POST['auth']) && $_POST['auth'] == 1) {
      $this->load->model('demo2_m');
      $data = $this->demo2_m->get_entries_by_state($this->input->post('state'));
  
      print json_encode($data);
    }
  }
}

The model

The mode consist of only 1 function which is returning me a query result with a where condition where I am passing the ‘state’ to select the entries. A very simple code igniter active records query.

class Demo2_m extends CI_Model {
  protected $table_name;
    
  function __construct() {
    parent::__construct();
    $this->table_name = 'temp';
  }
    
  function get_entries_by_state($state) {
    $this->db->select();
    $this->db->from($this->table_name);
    $this->db->where('state',$state);
    $query = $this->db->get();
      
    return $query->result();
  }
}

The view The view if you see is printing two links. The div container has ng-app=”demo2″ which means when I will declare a module in Angular JS, it will know which section of the application it needs to deal with. Inside this, if you see I have another div where I have set the ng-controller to “MyCtrl1”. Although it is not important but just to show that the controller’s scope is available here, I have added this and printed the base path.

<?php $this->load->helper('url');
  $this->load->helper('html');
?>
 
<div id="section-container" ng-app="demo2">
    This is some text
    <div ng-controller="MyCtrl1">
    Base path: {{basepth}}
    <ul>
        <li><?php print anchor('demo2#/view1','West Bengal'); ?></li>
        <li><?php print anchor('demo2#/view2','Maharashtra'); ?></li>
    </ul>
    <div ng-view></div>
</div>
 
</div>

The partials As you have seen, I have two links in my view which will use two different partials (I am calling them partials, but actually they are nothing but two separate views. It’s just that while loading these two views, I am not using the master template here.

Partial One
<h2>Entries for West Bengal</h2>
<table class="table table-bordered table-condensed table-strieped">
<tr>
    <th>Name</th>
    <th>Age</th>
    <th>City</th>
    <th>State</th>
</tr>
<tr ng-repeat="entry in entries">
    <td>{{entry.name}}</td>
    <td>{{entry.age}}</td>
    <td>{{entry.city}}</td>
    <td>{{entry.state}}</td>
</tr>
 
</table>

Partial Two
<h2>Entries for Maharashtra</h2>
<table class="table table-bordered table-condensed table-strieped">
<tr>
    <th>Name</th>
    <th>Age</th>
    <th>City</th>
    <th>State</th>
</tr>
<tr ng-repeat="entry in entries"> 
    <td>{{entry.name}}</td>
    <td>{{entry.age}}</td>
    <td>{{entry.city}}</td>
    <td>{{entry.state}}</td>
</tr>
</table>

The Javascript

Now here comes the main performer. In this javascript file, first I have declared an Angular module and there I have used the $route service. There are two routes define. The code says when ‘/view1’ use the template whose url is base_url + ‘demo2/view1’ and the controller for that is MyCtrl1. And there is also a catch all rule which will route the user back to view1 if it finds anything other than the two declared routes.

Then there are two functions which are the two controllers viz function MyCtrl1 and function MyCtrl2. In both the functions I have passed $scope and $http. The role of $http is to get the ajax data. You can compared it with $.ajax in jQuery.

I first initiated the entries. Then I made the ajax call. I have used the headers, url, method and the data parameters. And on the success I have assigned the data to entries. Remember, I have passed a json string. You can either pass HTML or JSON string.

// Declare app level module.
angular.module('demo2', []).
  config(['$routeProvider', function($routeProvider) {
    $routeProvider.when('/view1', {templateUrl: base_url + 'demo2/view1', controller: MyCtrl1});
    $routeProvider.when('/view2', {templateUrl: base_url + 'demo2/view2', controller: MyCtrl2});
    $routeProvider.otherwise({redirectTo: '/view1'});
  }]);
  
// The controller function
function MyCtrl1($scope, $http) {
  $scope.basepth = base_url;
  $scope.template = 'View 1';
    
  // Declare the entries
  $scope.entries = {}
    
  $http({
    headers: {'Content-Type': 'application/x-www-form-urlencoded'},
    url: base_url + '/demo2/select_entries',
    method: "POST",
    data: $.param({
      "auth" : 1,
      "state" : 'West Bengal'
    }),
  })
  .success(function(data) {
    $scope.entries = data;
  });
  
}
  
// The controller function
function MyCtrl2($scope, $http) {
  $scope.template = 'View 2';
    
  // Declare the entries
  $scope.entries = {}
    
  $http({
    headers: {'Content-Type': 'application/x-www-form-urlencoded'},
    url: base_url + '/demo2/select_entries',
    method: "POST",
    data: $.param({
      "auth" : 1,
      "state" : 'Maharashtra'
    }),
  })
  .success(function(data) {
    $scope.entries = data;
  });
  
}

Angular JS and Codeigniter

Angular JS and Codeigniter