CodeIgniter and Ajax Using JQuery Tutorial

This post is outdated, and might and might not work. Unfortunately I currently don’t have time to check and/or fix it. Sorry 😦

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:

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:

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:

function add()
{
    // if HTTP POST is sent, add the data to database
    if($_POST && $_POST['message'] != NULL) {
        $message['message'] = $this->input->xss_clean($_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.

function add($data)
{
    $this->db->insert('messages', $data);
}

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.

load->view(‘messages_list’) ?>
  1. message ?>

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:

$(document).ready(function() {
    $('#submit').click(function() {

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

        $.post("", {message: msg}, function() {
            $('#content').load("");
            $('#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 [download#1#size#nohits].

Or, if you prefer to get one by one,
[download#2#size#nohits]
[download#3#size#nohits]
[download#4#size#nohits]
[download#5#size#nohits]

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

Update: Need how to do this using JSON? Check CodeIgniter and Ajax Using jQuery tutorial using JSON.

Tagged , , , ,

157 thoughts on “CodeIgniter and Ajax Using JQuery Tutorial

  1. lawrence says:

    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. lawrence says:

    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 !!~

  3. little brain says:

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

    <script language="javascript" src="javascript/jquery.js">

    ps: I sent you email with the same comment 🙂

  4. little brain says:

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

  5. lawrence says:

    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…

  6. lawrence says:

    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…

  7. little brain says:

    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 🙂

  8. lawrence says:

    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 ?

  9. lawrence says:

    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 ?

  10. little brain says:

    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 🙂

  11. lawrence says:

    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…

  12. lawrence says:

    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…

  13. little brain says:

    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 🙂

  14. lawrence says:

    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

  15. lawrence says:

    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

  16. little brain says:

    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:

    load->view('header') ?>
    ... some html codes
    load->view('footer') ?>
    

    I put header.php and footer.php in my view folder 🙂

  17. lawrence says:

    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 ?

  18. lawrence says:

    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 ?

  19. little brain says:

    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 🙂

  20. lawrence says:

    thanks dude…you helped me alot…

  21. lawrence says:

    thanks dude…you helped me alot…

  22. little brain says:

    no problem mate. it’s nice to help 🙂

  23. koceng says:

    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….

  24. koceng says:

    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….

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

  26. speedovation says:

    very well written..Nice tutorial mate.

    Thank you

  27. speedovation says:

    very well written..Nice tutorial mate.

    Thank you

  28. […] CodeIgniter and Ajax using jQuery Ajax unter der Verschmelzung von CodeIgniter und jQuery. […]

  29. ical says:

    could u pls give me links for another jquery+CI tutorial?thx…

  30. ical says:

    could u pls give me links for another jquery+CI tutorial?thx…

  31. DShadow says:

    Thanks!!!

  32. DShadow says:

    Thanks!!!

  33. Leo says:

    Hello,

    I couldn’t figure out yet.
    Is your code working?
    I am having the same behaviour as your demo, however I can’t add more registries. Do I have to add an onClick event at the button?
    If yes please tell us how.

    Nice Tutorial!

    Leo

  34. Leo says:

    Hello,

    I couldn’t figure out yet.
    Is your code working?
    I am having the same behaviour as your demo, however I can’t add more registries. Do I have to add an onClick event at the button?
    If yes please tell us how.

    Nice Tutorial!

    Leo

  35. littlebrain says:

    hi Leo,

    the code is working. the $('#submit').click() is an onclick event wrapped using jquery library. the demo works 🙂

  36. littlebrain says:

    hi Leo,

    the code is working. the $('#submit').click() is an onclick event wrapped using jquery library. the demo works 🙂

  37. Nguyễn Khánh Hưng says:

    Not work on ie6

  38. Nguyễn Khánh Hưng says:

    Not work on ie6

  39. Anggun Firdaus says:

    nice articel..i’ve implemented, and it works..thx..

    but, can you writing articel about CI + ajax + thickbox or Ci + ajax + extjs..
    in simple case, can you explain how to insert data to database with JQuery ajax then load modal box with thickbox, after that the data load to extjs grid

    thx
    healthdict.blogspot.com

  40. Anggun Firdaus says:

    nice articel..i’ve implemented, and it works..thx..

    but, can you writing articel about CI + ajax + thickbox or Ci + ajax + extjs..
    in simple case, can you explain how to insert data to database with JQuery ajax then load modal box with thickbox, after that the data load to extjs grid

    thx
    healthdict.blogspot.com

  41. Morten says:

    You really should be more careful. You’re not validating any user input! This is dangerous! You should really take away the demo before any damage is done.

  42. Morten says:

    You really should be more careful. You’re not validating any user input! This is dangerous! You should really take away the demo before any damage is done.

  43. little brain says:

    you’re right. thank you for the notification 🙂

  44. little brain says:

    you’re right. thank you for the notification 🙂

  45. pioum says:

    Good tutorial, but i can’t download the files. and i can’t read the code of the view files

  46. pioum says:

    Good tutorial, but i can’t download the files. and i can’t read the code of the view files

  47. little brain says:

    fixed 🙂

  48. pioum says:

    thanx a lot

  49. pioum says:

    thanx a lot

  50. Sean-Paul says:

    Great tutorial! Thanks, huge help.

    One thing that I’m noticing on my site is that only the first input registers. If I put in more, they get inserted into the DB but the list does not update, I have to refresh the web page to see the new entries. Any ideas?

  51. Sean-Paul says:

    Great tutorial! Thanks, huge help.

    One thing that I’m noticing on my site is that only the first input registers. If I put in more, they get inserted into the DB but the list does not update, I have to refresh the web page to see the new entries. Any ideas?

  52. bowo says:

    good tutorial. bring me some light:). thanks

  53. bowo says:

    good tutorial. bring me some light:). thanks

  54. adam says:

    Hi, Brian where the $type variable is set?

    function view($type = NULL)
    {

    if ($type == “ajax”) // load->view(‘messages_list’, $data);
    ….
    }

    In yout code it does not appear anymore. is it set by jquery?

  55. adam says:

    Hi, Brian where the $type variable is set?

    function view($type = NULL)
    {

    if ($type == “ajax”) // load->view(‘messages_list’, $data);
    ….
    }

    In yout code it does not appear anymore. is it set by jquery?

  56. little brain says:

    ah yes, sorry for that, something wrong with the plugin. now should be ok.

    btw, I put it in view file, call it via jquery load function.

    $('#content').load("");

  57. Dinesh says:

    hi,

    i tried to this and it’s very useful. but when i using ajax. i couldn’t get validation_errors() results from CI controller.how can i get validation errors or DB update success message to view with ajax?

    please help me to do this.

    thank you

    Dinesh

  58. littlebrain says:

    hi Dinesh,
    you could create another view for form, and change the add function in controller to something like this:

    funtion add() {
      $this->load->library('form_validation');
      if ($this->form_validation->run() === FALSE) {
        $this->load->view('add_form');
      } else {
        // add to database
      }
    }
    

    then you call the add function via jquery to show the form.

  59. littlebrain says:

    hi Dinesh,
    you could create another view for form, and change the add function in controller to something like this:

    funtion add() {
      $this->load->library('form_validation');
      if ($this->form_validation->run() === FALSE) {
        $this->load->view('add_form');
      } else {
        // add to database
      }
    }
    

    then you call the add function via jquery to show the form.

  60. Alex Edwards says:

    Thanks!

    This was just what I needed for a little application I was working on. Much appreciated.

  61. Alex Edwards says:

    Thanks!

    This was just what I needed for a little application I was working on. Much appreciated.

  62. asdf says:

    should really escape your input…

  63. asdf says:

    should really escape your input…

  64. Thanks for giving the help. it is useful for me.

  65. AlexA says:

    Thanks for posting this, but neither demo nor code works correctly with Ie6. It was reported earlier but not answered. What might be the reason? After loading the page it is possible on add and show one new record. After that submit doesn’t change screen apperance but shown new record after browser refresh (but that not the way to use it)… Any advice?

  66. AlexA says:

    Thanks for posting this, but neither demo nor code works correctly with Ie6. It was reported earlier but not answered. What might be the reason? After loading the page it is possible on add and show one new record. After that submit doesn’t change screen apperance but shown new record after browser refresh (but that not the way to use it)… Any advice?

  67. bp says:

    Hi, I really need your help. I am using code ignitor for CRUD. Do you include jqeury lib in each of your view scripts. i just added an onclick event for a href link and in js i am popping up an alert box, it doestnt work.

    Thanks

  68. bp says:

    Hi, I really need your help. I am using code ignitor for CRUD. Do you include jqeury lib in each of your view scripts. i just added an onclick event for a href link and in js i am popping up an alert box, it doestnt work.

    Thanks

  69. Eric says:

    Anybody figured out why this doesn’t work properly on Internet Explorer? (I’m using IE8 and it still doesn’t work).

    The problem is that the very FIRST input to the form gets displayed, but second, third or anything after that do not get re-loaded onto the message-list view. However, the data gets inserted into database fine.

    It works on FireFox.

  70. Eric says:

    Anybody figured out why this doesn’t work properly on Internet Explorer? (I’m using IE8 and it still doesn’t work).

    The problem is that the very FIRST input to the form gets displayed, but second, third or anything after that do not get re-loaded onto the message-list view. However, the data gets inserted into database fine.

    It works on FireFox.

  71. Eric says:

    For those who are having the IE problem, here is the fix.

    The issue is in regards to IE caching and each time it attempts to load the “div” given the URL, it thinks it’s loading the same content.

    So, a quick fix would be to “confuse” IE that each time you post a comment, it is a new URL we are re-loading. And we can achieve this by giving a random integer attached to the end of the URL.

    Here’s the code :

    $(document).ready(function()
    {
    $(‘#submit’).click(function()
    {
    var msg = $(‘#message’).val();
    var load_url = “?random=” + Math.random()*99999;

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

    Hope that helps.

    You can also always use jQuery’s “append()” method to re-load the page, something like


    $(‘#content’).append(‘new comment that was just posted…!’);

  72. Eric says:

    For those who are having the IE problem, here is the fix.

    The issue is in regards to IE caching and each time it attempts to load the “div” given the URL, it thinks it’s loading the same content.

    So, a quick fix would be to “confuse” IE that each time you post a comment, it is a new URL we are re-loading. And we can achieve this by giving a random integer attached to the end of the URL.

    Here’s the code :

    $(document).ready(function()
    {
    $(‘#submit’).click(function()
    {
    var msg = $(‘#message’).val();
    var load_url = “?random=” + Math.random()*99999;

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

    Hope that helps.

    You can also always use jQuery’s “append()” method to re-load the page, something like


    $(‘#content’).append(‘new comment that was just posted…!’);

  73. Loy36 says:

    Software engineering researchers rarely write explicitly about their paradigms of research and their standards for judging quality of results. ,

  74. Pol77 says:

    The very first part of it has an express contradiction. ,

  75. Eddie Monge says:

    I would highly recommend changing your function (method) from the name ‘view’ to the name ‘display’ as it would most likely cause less confusion as view is the name given to displaying views in the MVC pattern.

    If you changed it, it would be like this:
    To load a view, the call is $this->load->view(‘welcome’);
    To load your display: $this->display();

    Less confusing when you aren’t using a CI method name for your functions.

  76. Eddie Monge says:

    I would highly recommend changing your function (method) from the name ‘view’ to the name ‘display’ as it would most likely cause less confusion as view is the name given to displaying views in the MVC pattern.

    If you changed it, it would be like this:
    To load a view, the call is $this->load->view(‘welcome’);
    To load your display: $this->display();

    Less confusing when you aren’t using a CI method name for your functions.

  77. порно видео курских студентов онлайн http://free-3x.com/ порно студенток школы free-3x.com/ порно в школе видео free-3x.com

  78. порно видео курских студентов онлайн http://free-3x.com/ порно студенток школы free-3x.com/ порно в школе видео free-3x.com

  79. indialike says:

    Very nice and useful tutorials to web designers,
    Thanks for posting.

  80. indialike says:

    Very nice and useful tutorials to web designers,
    Thanks for posting.

  81. jamifad says:

    For the life of me, I do not know. viagera Iowa Good joke 🙂 Why did the Indian wear a wig? To keep his wigwam.

  82. jamifad says:

    For the life of me, I do not know. viagera Iowa Good joke 🙂 Why did the Indian wear a wig? To keep his wigwam.

  83. Zaman says:

    thanks for sharing such a nice article.

  84. Zaman says:

    thanks for sharing such a nice article.

  85. gutasaputra says:

    im sorry. but the demo version, its wont show up. there is a some trouble with the lines of code. please help me to showing up the demo version. 🙂

  86. gutasaputra says:

    im sorry. but the demo version, its wont show up. there is a some trouble with the lines of code. please help me to showing up the demo version. 🙂

  87. sony says:

    really nice,thank you

  88. sony says:

    really nice,thank you

  89. Yogi says:

    Thank you.. Your tutorial inspired me..

  90. Yogi says:

    Thank you.. Your tutorial inspired me..

  91. Vladimir says:

    Hey

    Great CI/Ajax tutorial, keep up the good work 😉

  92. Vladimir says:

    Hey

    Great CI/Ajax tutorial, keep up the good work 😉

  93. excelln says:

    why don’t load view in your controller?

  94. excelln says:

    why don’t load view in your controller?

  95. this says:

    the demo doesnt work

  96. this says:

    the demo doesnt work

  97. Smart191 says:

    I am a big newbie. Where do you put the jquery code? Thanks!

  98. Blogregator says:

    Great tutorial! Than you!

  99. Kekz says:

    thanks a lot. works fine!

  100. Handayani Putrie says:

    demo version not show up…

  101. Gustavo says:

    Good tutorial! Congratulations!

  102. Thanhnd Dev says:

    hihihi, tks

  103. Guest says:

    You skipped the most important part:

    “The last, and maybe the most important part of this tutorial. …I assume you already know how to include a jquery script to your view.”

    If I already knew, I wouldn’t need the tutorial, would I?

  104. Devilmaycry says:

    Type your comment here.http://disqus.com/comments/

  105. Ovarbmag says:

    Hello 🙂

    I’m using this with a textarea box. If my text has more than one line it refreshes the whole page instead of using ajax itself. What is this about?

  106. Hari says:

    Very nice article. Thanks for sharing this!…

  107. Amit Gupta says:

    very nice and useful tutorial………..Thanks!

  108. […] now you have created CodeIgniter + AJAX jQuery, you’ll want to use JSON, javascript way to exchange […]

  109. juan says:

    Fix ortography please!

  110. Gayan Hewa says:

    Dude , thanks … it was kinda interesting. Its always helpful to have a simple tutorial. Because we have issues understanding the , simple things not the complex.

  111. As a newbie I get as much out of witnessing the pros thinking process as I do seeing the new code itself – even during mistakes or debugging.

  112. Underscore_05 says:

    thanks..

  113. Dhidyawdiyan says:

    nice..

  114. web design says:

    this is a great tutorial….because really put a real case for the tutorial…thanks for sharing this…

  115. myfacefriends says:

    thanks for the tuts! very help like us! more power mate!

  116. Someone says:

    Thanks.. nice tutorial..

  117. Jericrealubit says:

    tnxs! 😉 very nice tuts! keep it coming… 😉

  118. deste says:

    I appreciate your tutorial..
    Really very helpful for a codeigniter lamer like me! 😉
    Thank you so much, man.

  119. aditya says:

    is there any way i can make comments system like face book where on every post i can submit the comment or  do u know any know tutorial to  post comment on same page as you have in your blog, i will be very thankful

  120. Swapnil N kene says:

    Thanks dude

  121. Pabx promo says:

    very nice thanks 🙂

  122. Anggabs says:

    Thank you 🙂

  123. JustMe says:

    Thanks! Keep up the good work! Useful tutorial!

  124. Grifis says:

    Thanks for the tutorial, but how do I change the uri segment (3) to attach comments to a particular photo? Not print anything because I can not find the variable

  125. Good work. It helped me a lot.

  126. Really informative post, I am truly happy to post my comment on your
    blog. I’m glad that you shared this helpful info with us.

  127. sdf says:

    this is testing

  128. […] If I confused you it’s the 4.7 application example from here. The initial source code lies here but I have modified it in order to work with the latest release of CI and I quote all my MVC files […]

  129. It is recommended that you follow a strict diet plan and exercise regime in order to stay hydrated.
    Another important benefit that you can continue to use it.
    Fortunately, scientists have and still are today, the largest producers
    of tea.

  130. İyi paylaşım devamını bekleriz

  131. Yine iyi bir paylaşım olmuş sağol

Leave a reply to Sean-Paul Cancel reply