CodeIgniter AJAX With jQuery

The buzz-word of two years ago, AJAX, has quickly become an effective tool within every web developers toolkit. Effective uses of AJAX can speed up your application, decrease bandwidth usage and load times, as well as make your overall application much more user friendly.

In this CodeIgniter tutorial, I’ll show you how to implement AJAX, in a non-invasive manner, for the purpose of loading various dynamically generated lists. We’ll start by developing our application, a listing of blog posts that have either been published or are drafts, without AJAX. We’ll then implement AJAX in a manner that maintains our website’s functionality even if the user does not have Javascript enabled.

Starting the Application

Within a new CodeIgniter application, or a sandbox application if you have one, create a new controller. Within this tutorial we will call the controller Post.

// File: ./controllers/post.php
<?php
class Post extends Controller {
  function Post() {
    parent::Controller();
  }

  function index($status = NULL) {
    $this->load->model('posts');
    if ($status === NULL) {
      $template['posts'] = $this->posts->get_where(array('id >'=>0));
    } else {
      $template['posts'] = $this->posts->get_where(array('status'=>$status));
    }
    $template['partial'] = 'post/list';
    $this->load->view('view', $template);
  }
}

Here we have outlined the basic structure of our application as well as established the initial functionality. Our index() method will accept an optional parameter (status) and if that parameter is not defined we will just return all of the posts within our blog. You may notice I have an odd query if a status has not been defined (array(’id >’=>0)) - this is just a quick little hack so I didn’t have to write two different functions within my model. You could easily change this to return all of the posts, without a hack’ish query, if you’d like.

The controller retrieves a list of posts, based on certain parameters, as well as setting a variable called partial. We’ll be using the partial variable shortly, as I show you how to implement partial views quickly and easily within CodeIgniter. For now, let’s get our model completed so we can get a clearer picture of what this controller is accomplishing.

// File: ./models/posts.php
<?php
class Posts extends Model {

  var $_table = 'posts';

  function Posts() {
    parent::Model();
  }

  function get_where($params = array()) {
    if (count($params) > 0) {
      $query = $this->db->get_where($this->_table, $params);
      if ($query->num_rows() > 0) {
        return $query->result_array();
      }
    }
    return FALSE;
  }
}

If you’ve viewed my other tutorials you will have probably noticed a trend, especially within my models, of testing for positives. In the above get_where() function I whittle away the possibilities of the function failing by first making sure a parameter was passed and then by making sure a result set was returned from the database. Only then do I return that result set, as an array, to the controller. I find testing for positives, and assuming a failure, is the easiest way to ensure you gracefully degrade your application upon failure.

Now, let’s get to our views - we’re almost done with our application and we can start playing with the AJAX! Let’s first create our master view file, which will load our header and footer, as well as the partial that is defined within our controller.

// File: ./views/view.php
<?php $this->load->view('_global/header'); ?>
<?php $this->load->view($partial); ?>
<?php $this->load->view('_global/footer'); ?>

Another standard of mine is the _global folder - I like to use this as it forces the folder to rest at the top of Windows Explorer where it is readily accessible. This way, I don’t have to go searching for it from application to application (based on the other folder names) - I know it is always at the top. Let’s finish up our header and footer files, we’ll then move on to the partial view that we called from the index() method within our Post controller earlier.

// File: ./views/_global/header.php
<html>
  <head>
    <title>CodeIgniter Ajax Tutorial</title>
    <link href="<?php echo base_url(); ?>assets/css/style.css" media="screen" rel="stylesheet" type="text/css" />
    <script type="text/javascript" src="<?php echo base_url(); ?>assets/js/jquery-1.2.6.min.js"></script>
    <script type="text/javascript" src="<?php echo base_url(); ?>assets/js/ajax_tut.js"></script>
  </head>
  <body>
    <div id="wrapper">
      <div id="header">
        <h1>CodeIgniter Ajax Tutorial</h1>
        <div id="nav">
        <ul>
          <li><?php echo anchor('', 'All Posts'); ?></li>
          <li><?php echo anchor('published', 'Published'); ?></li>
          <li><?php echo anchor('draft', 'Drafts'); ?></li>
        </ul>
        </div>
      </div>
// File: ./views/_global/footer.php
    </div>
  </body>
</html>
// File: ./views/post/list.php
<div id="loading">Loading...</div>

<div id="list">
<?php
  foreach ($posts as $post) {
    echo '<p><h3>' . $post['title'] . '</h3>
            <span class="created_on">Posted on: ' . $post['created_on'] . '</span></p>';
  }
?>
</div>

Our partial view (post/list.php) doesn’t really need much explaining - all we’re doing is cycling through all of the posts returned from our model and echoing out their title and the date in which they were created.

The Final Touches

Our application is almost complete! It’s now time to put the final touches on there to make sure it works. The first thing we want to do is create our database table and pump some test data into it - here’s a SQL dump to make that easier for you:

CREATE TABLE IF NOT EXISTS `posts` (
  `id` int(10) unsigned NOT NULL auto_increment,
  `title` varchar(255) NOT NULL,
  `status` varchar(10) NOT NULL,
  `created_on` date NOT NULL,
  PRIMARY KEY  (`id`)
) ENGINE=MyISAM  DEFAULT CHARSET=utf8 AUTO_INCREMENT=4 ;

INSERT INTO `posts` (`id`, `title`, `status`, `created_on`) VALUES
(1, 'First post.', 'published', '2008-05-27'),
(2, 'This is the second post.', 'published', '2008-05-27'),
(3, 'This is a draft.', 'draft', '2008-05-28');

Now we just need to make a few configuration changes - your settings may be different for everything below, but this will give you a good direction as to where to start. First of all, make sure your config.php is configured correctly - particularly the base_url setting.

// File: ./config/config.php
$config['base_url']	= "http://localhost/ajax_tut/";

Now, let’s make sure we can actually connect to our database.

 // File: ./config/database.php
$db['default']['hostname'] = "localhost";
$db['default']['username'] = "root";
$db['default']['password'] = "";
$db['default']['database'] = "ajax_tut";
$db['default']['dbdriver'] = "mysql";

We’re going to autoload the database library and a helper to make development generally easier.

// File: ./config/autoload.php
$autoload['libraries'] = array('database');
// File: ./config/autload.php
$autoload['helper'] = array('url');

Finally, if you look back over our header view file you will see that our anchor() functions are linking to a single segment. Of course, we’re not going to make a class for each of these segments (which would be CodeIgniter’s default functionality) we’re just going to route them to the index() method of the Post class.

// File: ./config/routes.php
$route['([a-zA-Z]+)'] = 'post/index/$1';
$route['default_controller'] = 'post';

If you’ve loaded the site up you’ve probably noticed it’s pretty hideous - so let’s make it pretty really quick. Once again, I am going to throw one of my standards at you - the assets folder. This is where I store my CSS, Javascript, and image files and it can be found at my webroot. If you review the code within the header view file you will notice I use base_url() to ensure these static files get an absolute path and always work. It takes the guess work out of referencing these files which is a problem a lot of newcomers to the CodeIgniter framework, or any MVC framework, have.

// File: ./assets/css/style.css
body {
    font:0.8em Verdana;
    text-align:center;
}

a:link, a:active, a:hover, a:visited {
    color:blue;
    text-decoration:none;
}

#wrapper {
    margin:0 auto;
    text-align:left;
    width:600px;
}

#nav {
    background:#DDD;
}

#nav a {
    padding:10px;
}

#nav a:hover {
    background:#FFF;
}

#nav ul {
    padding:5px;
    list-style:none;
}

#nav li {
    display:inline;
    margin-right:1.5em;
}

#loading {
    display:none;
    font-weight:bold;
    text-align:center;
}

#list h3 {
    display:inline;
}

.created_on {
    color:#AAA;
    font-size:0.7em;
}

Go ahead and test our application out - it’s pretty basic and should work with no problem. Unfortunately, we’ve got an annoying page load between every request and we don’t really think that’s necessary (plus, this is an AJAX tutorial and we haven’t covered it yet).

On the next page we’ll implement AJAX in a non-invasive manner, so our website functions as it does now for users with Javascript disabled. We’ll even crank out a small library that will tell us whether a request is via AJAX or not!

Pages: 1 2

17 Responses to “CodeIgniter AJAX With jQuery”

  • Nice tutorial - I’ve been struggling with CI and jQuery so hopefully this will help (to be fair, I’ve probably been struggling with the intricacies of CI more than the jQuery). Fitting in web development with a full time day job (which is not at all web related) and a young family isn’t easy, as you know.
    Maybe I should join the USAF to get a bit of time to myself… ;o)

  • Oh God yes, a proper CI and jQuery tutorial at last!

    Totally sweet stuff, although I don’t think I’ll be using CI to work on my new site anymore :(

    And good thinking about the library. You’re a genius.

  • @Martin
    I wish it was that easy - right now I sleep from 0100 - 0600, work from 0700 - 1900, and code from 2000 - 0100. It’s definitely starting to take it’s toll on me though - I do a lot of catching up on sleep my one day off per week.

  • Hooray! Thanks for the tutorial… I’ve been in the process of switching from Prototype over to jQuery and this intro is perfect! Now to delve into the UI features of jQuery… Thanks Michael!
    Keep up the great work!

  • Is it possible to have a link to an example. Readers will then be able to instantly check to see if the code would be useful to themselves.

  • hi michael! your tutorial translated in italian..
    bye neryo

    http://www.programmazione-web.com/tutorial-codeigniter-integrazione-ajax-jquery.php

  • luke

    Thanks a lot! This was a major missing piece for me.

  • hellooo
    thanks for your tutorial

    can you help me give me” a simple program with codeigniter and jquery” please , I am newbie and very need a simple program with jquery and codeigniter” thank you for atention”

    I am come from indonesia mY email krida84@yahoo.co.id

  • @krida
    This tutorial is a program with CodeIgniter and jQuery - what specifically were you looking for?

  • liam

    Nice tutorial mate! ^^, Impressive work.

    By the way I have a question here. How can I place to the get_where() an order_by()? so I can sort my query result to a descending order.

    Thanks and keep up the good work.

  • @liam - it would be 2 seperate commands

    $this->db->order_by('created_on', 'DESC');
    $this->db->get_where('posts', array('category_id' => 1));

    If in PHP5 you can use method chaining as described at the bottom of the CodeIgniter Active Record User Guide.

  • hazy

    Michael

    An interseting a well presented tutorial. So how might we take it further? You have a “static” page elements being thrown by post/list. What if we wanted to include the ‘id’ field anchor’d in some way to show say comments associated with that posting, ie dynamic content back from the ajax call. How might you go about that? Of course we need another function in our Post controler but is it a problem that we dont know what anchors we will have so cant code for them in JS document.ready? Maybe that’s just a JS issue and “not in scope” here.

  • kanelit

    when i download .from web.i test it diplay the blank page.

  • @kanelit: When you download what? The zip file including the example files? Are you running them off of a web server?

  • kanelit

    i just run it on localhost.for me i am a nebie.sorry i need to test run.i used apache2triad.
    i load form full package of your tutorial.thanks

  • kanelit

    @Michael Wales:now i find the problems(it is my flase) thanks.it is nice tutorial i am looking for with CI and AJAX.