Adding AJAX to Codeigniter with jQuery

Today we will talk about adding AJAX to the PHP development framework called CodeIgniter. When I started to work with this framework I found rather strange that there was not too much information about how to integrate AJAX into it, since it is a relatively known framework and AJAX methodology is very common in web development. When I had the need to integrate AJAX using the JavaScript framework jQuery into my application made with CodeIgniter, I have been looking for information about this subject on the Internet and the truth is that, besides being very scattered, it is not very abundant and not very clear, so here it is my contribution from what I have learned, hopefully useful.

Developing the controller

Well, in order to explain the integration of jQuery into CodeIgniter we will put a scenario to work with. In a sports site we need to edit the record of a match, for that we have a drop down list (select HTML tag) which shows a number of tournaments and another empty drop down list which has the matches for each tournament. The matches’ list must be filled in (using AJAX) every time the tournaments list changes the tournament displayed, so, if we select a different tournament, the matches list must be filled with the matches for that tournament. To do this we have to create our tournament editing controller with this code:

class Tournament_record extends Controller {

 public function __construct()
 {
 parent::Controller();
//Loading the tournament model
 $this->load->model('tournament_model');
 }

...
...

 public function edit_record()
 {
//Get all the tournaments in the system
 $data["tournaments"] = $this->tournament_model->get_tournaments();
//Loading the view for the record edition
 $this->load->view('edit_record',$data);
 }
...
...
}

With the above code, we already have our controller for editing records, now it comes one of the most important parts of the process, and it is to create the view for editing the records, where we are going to put the JavaScript code with jQuery, which will make data requests via AJAX. The code should look like this:

//We include the jQuery framework from their own site
<script type="text/javascript" src="http://code.jquery.com/jquery-latest.min.js"></script>  
<script type="text/javascript">
 $(function() { 
//When the DOM is ready, we disable the matches list
 $('select#match_list').attr('disabled',true);
 });

 function activate_match()
 {
 var tnmt_id = $('select#tournament_list').val(); //Get the id of the tournament selected in the list
 $.ajax({
 type: 'POST',
 url: '<?php echo base_url(); ?>index.php/match/list_dropdown', //We are going to make the request to the method "list_dropdown" in the match controller
 data: 'tnmnt='+tnmt_id, //POST parameter to be sent with the tournament id
 success: function(resp) { //When the request is successfully completed, this function will be executed
 //Activate and fill in the matches list
 $('select#match_list').attr('disabled',false).html(resp); //With the ".html()" method we include the html code returned by AJAX into the matches list
 }
 });
 }
</script>

<strong>Tournament:</strong>
<select id="tournament_list" onchange="activate_match()">
 <?php
 foreach($tournaments as $tournament)
 {
 echo "<option value='{$tournament["id"]}'>{$tournament["name"]}</option>";
 }
 ?>
</select>
<br />
<strong>Match:</strong>
<select id="match_list" onchange="show_clips()">

</select>

With the above code we have made the AJAX request to the matches controller (“match”), specifically to the method list_dropdown(). I must point out one thing that gave me some headaches until I discovered it: you have to be really careful about including the “index.php” in the URL of the target controller, because if you do not include it, the AJAX request will not work unless you have a .htaccess file in your web directory where you have a rule to avoid putting in the url “index.php”.

The method list_dropdown() will process the request, bringing tournament matches and filling the list view. Here it is the controller code for matches:

class Match extends Controller {

 public function __construct()
 {
 parent::Controller();
 $this->load->model('match_model');
 $this->load->model('team_model');
 }

 public function index()
 {

 }

 public function list_dropdown()
 {
 $tnmnt_id = $this->input->post('tnmnt'); //Read the tournament id sent by POST
 $matches = $this->match_model->get_match_by_tournament($tnmnt_id); //Get the matches list for that tournament from the DB
 $teams = array(); //We store the names of the teams in the form "team_id" => "team_name"
 if(!empty($matches))
 {
     foreach($matches as $match)
     {
         if(!array_key_exists($match["teama"], $teams))
         {
             $team_name_A = $this->team_model->get_team_name($match["teama"]);
             $teams[$match["teama"]] = $team_name_A;
         }
         if(!array_key_exists($match["teamb"], $teams))
         {
             $team_name_B = $this->team_model->get_team_name($match["teamb"]);
             $teams[$match["teamb"]] = $team_name_B;
         }
     }
 }
 $data["matches"] = $matches;
 $data["teams"] = $teams;
 $this->load->view('list_dropdown_view',$data);
 }
}

Finally, we just need to create the view for the drop down list of matches. This will not be more than just a file where we are going to write all the tags option for the drop down list to be loaded into the select tag of matches. The code would be:

if(empty($matches))
{
    echo "<option value=''>No available matches</option>";
}
else
{
    foreach($matches as $match)
    {
        echo "<option value='{$match["id"]}'>{$teams[$match["teama"]]} - {$teams[$match["teamb"]]}</option>";
    }
}

With this, we would have our view and we would have completed our integration of jQuery into CodeIgniter in order to be able to use AJAX. As result of all this work, in the view of match edition, every time you change the selected item in the list of tournaments, it will update the list of matches for that tournament.

13 thoughts on “Adding AJAX to Codeigniter with jQuery

Leave a Reply

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