CodeIgniter and Ajax Using JQuery Tutorial

May 27th, 2008

I created this tutorial because I was having a hard time finding good simple CodeIgniter + JQuery tutorial for newbie like me. The one I found, created by MR Forbes, is hard to understand and apparently isn’t working. Another one, pr0digy’s, is using Mootools for the AJAX framework.

So I decided to create my own CodeIgniter and JQuery tutorial based on pr0digy’s tutorial. I’m assuming you already know how to code using CodeIgniter. If you’re new to CodeIgniter, you need to find others tutorial first. The videos given in CodeIgniter’s site is a good start.

This tutorial is about creating simple CodeIgniter + database + ajax system. User will be shown a form to post a message. Then after he/she press the submit button, the system will save the message using ajax and then show the message. You could see the result first if you want.

Database

The first thing we need to do is creating a table to save the message. For this tutorial, We will use this:

1
2
3
4
5
CREATE TABLE IF NOT EXISTS `messages` (
  `id` tinyint(4) NOT NULL AUTO_INCREMENT,
  `message` varchar(256) NOT NULL,
  PRIMARY KEY  (`id`)
)

Controller

Then, we need to create a controller. My controller is named message. You could name your controller any name you like. After that, create 2 functions/methods, view and add.

view is used to get the default view and list of messages from the database. The codes are:

1
2
3
4
5
6
7
8
9
10
function view($type = NULL)
{
    // get data from database
    $data['messages'] = $this->Message_model->get();
 
    if ($type == "ajax") // load inline view for call from ajax
        $this->load->view('messages_list', $data);
    else // load the default view
        $this->load->view('default', $data);
}

We fetch messages from the database using Message_model->get() function. Then the data is passed to the view. Here, we have 2 views called. One for the default view, where we called the page using message/view, and the other is for calling from ajax.

add is a proccess used to insert the message to the database. The codes are:

1
2
3
4
5
6
7
8
9
function add()
{
    // if HTTP POST is sent, add the data to database
    if($_POST && $_POST['message'] != NULL) {
        $message['message'] = $_POST['message'];
        $this->Message_model->add($message);
    } else
        redirect('message/view');
}

This function is accessed when we press the submit button from the form. This function will save the message using Message_model->add() function.

Model

The next thing we need to create is the model. I use Message_model for the name. Here we create two functions, add and get. add is a function to insert the data into the database. get is a function to retrieve data from database. I think the codes are pretty self-explainatory, but you could drop me a message if you need some explainations on the codes.

1
2
3
4
function add($data)
{
    $this->db->insert('messages', $data);
}
1
2
3
4
5
6
7
function get($limit=5, $offset=0)
{
    $this->db->orderby('id', 'DESC');
    $this->db->limit($limit, $offset);
 
    return $this->db->get('messages')->result();
}

View

I use 2 files for view section. default.php and message_list.php. The message_list is used for displaying the messages taken from the database.

1
2
3
4
5
6
7
8
<div id="form">
    <input type="text" id="message" name="message" />
    <input type="submit" id="submit" name="submit" value="submit" />
</div>
<div id="content">
<?php $this->load->view('messages_list') ?>
 
</div>
1
2
3
4
5
<ol>
<?php foreach ($messages as $message): ?>
    <li><?= $message->message ?></li>
<?php endforeach ?>
</ol>

Hey, Where’s the JQuery?

Here we go. The last, and maybe the most important part of this tutorial. So, we the our controller, we had the model, and we had the views. I assume you already know how to include a jquery script to your view. The jquery codes are this:

1
2
3
4
5
6
7
8
9
10
11
$(document).ready(function() {
    $('#submit').click(function() {
 
        var msg = $('#message').val();
 
        $.post("<?= site_url('message/add') ?>", {message: msg}, function() {
            $('#content').load("<?= site_url('message/view/ajax') ?>");
            $('#message').val('');
        });
    });
});

So, when we click the submit button, the javascript will take the value of input textbox then send it to message/add using post method. When the action succeed, the script will call message/view/ajax. Note the ajax keyword. It will call the message_list view instead of the default one. Then the view will replace the content in div#content tag.

Well done. You could see the demo I made from the tutorial.

You could download the whole files used in this tutorial in tutorial.zip (1.98 KB).

Or, if you prefer to get one by one,
controller: message (904 bytes)
model: message model (583 bytes)
view: default (782 bytes)
view: message_list (111 bytes)

I hope this tutorial helps newbie like me. If you have any question, just drop a comment below ;)

Comments

19 Responses to “CodeIgniter and Ajax Using JQuery Tutorial”

  1. lawrence on May 30th, 2008 10:00 am

    i wondering how to include the jquery.
    cause i also been following MR Forbes example..
    although can get the first page running. But when it load back the page again, it not running anymore.

    i put my file like this :

    www/codeigniter/system <– this is for all the system files.

    i put my javascript jquery
    www/codeigniter/javascript/jquery.js

    in the view, i include like this

    it can run when i type my URL like this
    localhost/codeigniter/index.php/message

    but not when
    localhost/codeigniter/index.php/message/view

    can guide me how to really put the jquery files ?
    thanks !!~

  2. little brain on May 30th, 2008 10:38 am

    have you put the javascript link in your head tag in view? yours would be like this:


    ps: I sent you email with the same comment :)

  3. little brain on May 30th, 2008 10:43 am

    oh well, the code is filtered. sucks.
    here’s how to include your javascript:
    http://kriwil.pastebin.com/d2a83eb9b

  4. lawrence on May 30th, 2008 1:11 pm

    the link works.

    before this i found that when the URL like:
    localhost/codeigniter/index.php/message/view

    when it got another / after index.php
    then i have to include extra “../” to the original “../jquery.js”.

    if localhost/codeigniter/index.php/message/view/
    another / behind view.

    then i have include “../../” to the include link.

    but your reference link solve the problem.
    it help lots…..
    thanks lots…

  5. little brain on May 30th, 2008 1:17 pm

    glad I could help :)

    yes, we have to use absolute url when dealing with link in CI, because CI url structure is like directory structure :)

  6. lawrence on May 30th, 2008 5:12 pm

    for this part…
    $(document).ready(function() {
    $(’#submit’).click(function() {

    var msg = $(’#message’).val();

    $.post(”", {message: msg}, function() {
    $(’#content’).load(”");
    $(’#message’).val(”);
    });
    });
    });

    how could i add more element to it ?
    you are using json way ?

  7. little brain on May 30th, 2008 7:28 pm

    if you want to add more element, you could see this code: http://kriwil.pastebin.com/f1bcc82a4

    no, I’m not using json yet. I’m using regular jquery method. Maybe I’ll write tutorial about that later :)

  8. lawrence on June 2nd, 2008 9:23 am

    thanks for the reply…
    here is another question. i have been figure it for 2 days.

    for php require_once, include…
    i cant use base_url() or BASEPATH.
    not sure what happen here…
    i did it same way as how i do with the javascript.

    can help me with that ?
    thanks…

  9. little brain on June 2nd, 2008 11:38 am

    you could use the BASEPATH.
    I just tried and it worked. The BASEPATH defines your CI system folder.

    So if you want to include a file from view folder, you should write like this:

    require_once(BASEPATH . 'application/views/test.php');

    why would you want to use require_once anyway? if you want to include some function, you could create it as CI plugin. It’s more elegant in CI :)

  10. lawrence on June 2nd, 2008 12:28 pm

    i want to include files like header and footer that shared.

    so in CI include is not preferred?

    hmm..i think i can get your idea….
    just use controller to load view of header and footer….

    that might works….haha….thanks

  11. little brain on June 2nd, 2008 12:34 pm

    if you want to include another view files in view folder, you could use
    $this->load->view('filename');
    in the view file :)

    it’s the same with inlcude file, only it’s done the CI-way :)

    I did that in every website I created. like this:

    <?php $this->load->view('header') ?>
    ... some html codes
    <?php $this->load->view('footer') ?>

    I put header.php and footer.php in my view folder :)

  12. lawrence on June 2nd, 2008 12:48 pm

    oh…yeah…if the view files is out of view folder…
    then i will have bit problem to included.

    so how about css? same way how the jquery file done ?

  13. little brain on June 2nd, 2008 12:56 pm

    yup, if the file is not the view folder, maybe the only way is using that require_once method ;)

    yes, css is using the same way with jquery :)

  14. lawrence on June 2nd, 2008 2:05 pm

    thanks dude…you helped me alot…

  15. little brain on June 2nd, 2008 2:08 pm

    no problem mate. it’s nice to help :)

  16. koceng on June 6th, 2008 2:48 pm

    Bro, ajarin dong CI dengan AJAX. ane masih belum ngerti padahal udah belajar dari tutorial orang banyak. buat back end program dengan AJAX dalam CI.

    mo hujan no oject becceckk….

  17. Daily Find #77 | TechToolBlog on June 9th, 2008 11:33 pm

    [...] CodeIgniter and AJAX using jQuery [...]

  18. Belajar cepat Code Igniter and JQuery Ajax Tutorial « Krida on June 20th, 2008 5:41 pm

    [...] klik disini [...]

  19. Codeigniter help site « Ismail Muhammad Noman’s Weblog on July 1st, 2008 1:25 pm

Leave a Reply