A Quick Code Igniter and JQuery Ajax Tutorial

This tutorial assumes a basic working knowledge of Code Igniter. If you have never used CI before, please refer to the framework documentation

In the old days (2 years ago), working the Javascript magic to create a cool AJAX based event took a fairly decent working knowledge of the mechanisms behind the process.

With the increasing popularity of Javascript libraries however, this type of functionality became available to the web site hobbyist, and was made much easier for the web site professional.

The following step-by-step tutorial will show you how to combine the power of JQuery (a javascript library that weighs in at about 20k) with Code Igniter (a PHP framework based on the MVC design pattern) to quickly and painlessly pass a record ID through the javascript and over to the server, where it will be passed to a mysql database, used to retrieve some data, and sent back to the page for display.

Step 1
We begin by assuming that you have a div with an id of content, which is where you would like your freshly retrieved data to display, once it has been freshly retrieved. For this exercise, you have already taken an action to call your javascript function with a record ID parameter.

The first thing you need to do, is make sure JQuery is being loaded, and to create a function for your AJAX request.



Step 2:
Next, youll use the JQuery function load, and attach it to your content div:

function get_record_id(record_id) {
     $('#content').load()
}

Step 3:
The load function accepts three arguments. The page to be called on the other side of the HTTPRequest, the array to pass through the POST, and a callback function. It looks like this:

function get_record_id(record_id) {
     $('#content').load(/controller/method,p,function(str){

	 });
}

Lets go back to that. Code Igniter URLs are created by calling the name of your controller, followed by the function inside the controller class that will handle your request. If your server does not support mod-rewrite, you may also need to append an index.php to the beginning. The str inside the callback function is the results of your AJAX request. There isnt much use for the str when using the .load function, but it does come in handy using the other JQuery AJAX functions – $.post and $.get, which I assume are self explanatory.

Step 4

var p = {}; //instantiate the array
p[record_id] = record_id //assign your record_id variable to it.

Thats all there is to it. Your final javascript function looks like this:

function get_record_id(record_id) {
     var p = {};
     p[record_id] = record_id
     $('#content').load(/controller/method,p,function(str){

     });
}

Step 5
On the CI side, you have a controller and method setup something like this:

class Controller
{
   function Controller()
   {
       parent::CI;
   }

   function method()
   {
   }
}

The important part is the method() function, as it will contain some of the code we need to make things happen.

Step 6
The first thing you need to do on the CI side is retrieve the value passed through the request object. This is simple enough, using $_POST[record_id]. You also want to load up your database model so you can get the record out of your database. So, well load the database library, and then load the actual model. Then, we want to send the record ID to the database, get the resulting data, and pass it back out to the request. our function starts to look like its doing something useful pretty quickly.

function method()
{
   $record_id = $_POST[record_id];
   //set the record ID
   $this->load->library(database);
   //load the database library to connect to your database
   $this->load->model(records);
   //inside your system/application/models folder, create a model based on the procedure
   //outlined in the CI documentation
   $results = $this->records->get_record($record_id);
   //get the record from the database
}

Step 7
At this point, we need to go into our records.php file in the model folder. Since Code Igniter uses a Model-View-Controller structure, database activity, server-side processing, and client-side display should be as separate from one another as possible. You dont NEED to do this for Code Igniter to do its thing, but its good practice.

Inside the records.php file, well create a method called get_record to match the method referenced above. Well use it to get a record by its primary key of ID, put the resulting data into an array, and send it back to the controller, out to the view, and ultimately into the content div we started with.

function get_record($record_id)
{
   $this->db->where(ID,$record_id);
   //we want the row whose ID matches the value were passing in
   $query = $this->db->get(record_table);
   //get the table and put it into an object named $query
   $row = $query->row();
   //gets the first row of the resulting dataset.  In this case, only 1 row will ever be returned
   $results[record][$row->ID][name] = $row->name;
   //here, we create a multi-dimensional array holding the returned values
   //based on the key.
   return $results;
   //send the record back to the controller
}

The trickiest part of this section is the array. It seems pretty complex from here, but youll see soon enough how it breaks down into something more manageable as we go along.

Step 8
Were back to the controller again, and we have one more line to add – this time to pass the resulting data into a view to be formatted and printed to the content div. The whole method() function now looks like this:

function method()
{
   $ID = $_POST[record_id];  //set the record ID
   $this->load->library(database);
   //load the database library to connect to your database
   $this->load->model(records);
   //inside your system/application/models folder, create a model based on
   //the procedure outlined in the CI documentation
   $results = $this->records->get_record($record_id);
   //get the record from the database
   $this->load->view(AJAX_record,$results);
}

Step 9
The AJAX_record.php file should be in your system/application/views folder. Keep in mind, that when you pass an array to a view (in this case the $results array), it will be exploded inside the view. So, the path to your record is now $record, instead of $results[record]. Also inside will be your standard HTML markup, and something like this:

< ?php foreach($record as $id=>$value) { ?>
     The name associated with this record is: < ?php print $value[name];?>
< ?php } ?>

This output is what php is sending to the request object, and is also what gets loaded into the content div. Code Igniter and JQuery make it that easy to dynamically load data using AJAX.

  • gabriel

    What do I think? I think, “Thank You!”
    Thanks to you I have finally wrapped my little brain around the proper integration of Ajax functionality into the MVC design pattern. All my ugly hacks are now (thankfully!) obsolete :)

  • http://rafiq7s@yahoo.com rafiq7s

    Thanks a lot. Very helpful for me.

  • Nikola

    Great tutorial!

  • http://me@me.eu Me

    Detailed ! Very good

  • Beez

    Thank You.

  • Harm

    Thanks for reposting this, this is very helpful to me. Very clear tutorial !

  • http://enjoyfrancis.com enjoyfrancis

    This is what i’m looking for.
    Super Thanks!

  • ranjith

    Great Outstanding tutorial Helped me a lot!

  • http://www.topsella.com LEo Peralta

    Nice! Helps a lot until now for newbies like me. Thanks..

  • http://nigwoko nigwoko

    great tut!

  • Rocky

    Thank You.

  • http://www.rutadirecta.com Antonio Vazquez

    Algo asi pensé que tendria que ser, gracias por aclararlo.

    Saludos!

  • Guest

    Thanks for the tutorial

  • Guest

    8-)

  • Anonymous

    :D that sound’s great..!!!!

    Very clean and simple, tutorial; perfect for newbies like me… :P

  • prabhash h

    8-)

  • uk

    really a nice tutorial and a nice example for using Ajax and CodeIgniter.

  • dyah

    thank you!. works like a charm.

  • Rajesh

    8-)Thanks man for making my day………… 8-)

  • subash niroula

    $(‘#content’).load(/controller/method,p,function(str){

    });

    the above code doesnot work while testing the documentation.But why??? I m in trouble . PLZ help me!!!!!!

    • admin

      subash,

      you’ll need to change controller to match the name of your main controller file in system->application->controllers. the default for CI is welcome.php.

      method is the name of the function inside the controller. for example function hello_world(){echo ‘hello world';}

      using this example, you would write it out as $(’#content’).load(/welcome/hello_world,p,function(str){})

      i hope that helps.

  • Me

    subash,

    you’ll need to change controller to match the name of your main controller file in system->application->controllers. the default for CI is welcome.php.

    method is the name of the function inside the controller. for example function hello_world(){echo ‘hello world';}

    using this example, you would write it out as $(’#content’).load(/welcome/hello_world,p,function(str){})

    i hope that helps.

  • cvxcv

    8-)

  • Mehedi Hasan

    WOW!!! Thanks a lot for this great tutorial.

    Thanks
    Mehedi Hasan
    Web Developer Bangladesh
    http://www.mehedibd.com

  • Anonymous

    Vad tänker du på…

  • Anonymous

    :* :* :* :* :* :* :* :* :* :* :* :* :* :* :* :* :* O:-) &gt;:o :) ;) :'( 8-) :( :* :-D =-O =-X :-[ :-$ :-$ :-P :-E :-E

  • niraj

    :)

  • Maqui

    Why am i getting this error? Please help. Thank you!

    $(“#page-container”) is undefined
    get_entry_uid(1)show_all_entries (line 71)
    function onclick(event) { get_entry_uid(1); }(click clientX=411, clientY=220)2 (line 2)
    [Break on this error] $(‘#page-container’).load(index.php/hotline/update_entry,p,function(str){rn

    <script type=”text/javascript”>
    function get_entry_uid(entrant_uid) {
    var p = {};
    p[entrant_uid] = entrant_uid
    $(‘#page-container’).load(index.php/hotline/update_entry,p,function(str){
    });
    }
    </script>

    <div id=”page-container”>
    </div>

  • Me

    Maqui,

    that error message would suggest that you don’t have an element with an id of page-container. If you post a link to your test page, I or one of the visitors to this entry may be able to help you further.

  • ifeanyi

    Nice article.

  • fgsfds

    great tut man

  • mica

    Thanks a lot

  • http://blogregator.net blogregator

    Great Tutorial! Thank you!

  • http://doroubna.com Qusai

    oh thank you …. it is helpful :)

  • http://twitter.com/villegas_jm Juan Manuel Villegas

    Good tutorial, should fix ortography to be perfect!

  • http://twitter.com/villegas_jm Juan Manuel Villegas

    Good tutorial, should fix ortography to be perfect!

  • http://www.facebook.com/arnas.risqianto Arnas Risqianto

    At step 6:
    $record_id = $_POST[record_id];
    It is not safe and generate vulnerability because input not filtered.
    It should be:
    $record_id = $this->input->post('record_id');
    Also same with step 8.
    Refer to this page:
    http://codeigniter.com/user_guide/libraries/input.html

    Also at step 6:
    $this->load->model(records);
    $this->load->library(database);

    should be:
    $this->load->model('records');
    $this->load->library('database');
    (missing quote)

    At step 5:
    When creating controller, it should extend to Controller. Refer to this page: http://codeigniter.com/user_guide/general/controllers.html

  • http://www.facebook.com/arnas.risqianto Arnas Risqianto

    At step 6:
    $record_id = $_POST[record_id];
    It is not safe and generate vulnerability because input not filtered.
    It should be:
    $record_id = $this->input->post('record_id');
    Also same with step 8.
    Refer to this page:
    http://codeigniter.com/user_guide/libraries/input.html

    Also at step 6:
    $this->load->model(records);
    $this->load->library(database);

    should be:
    $this->load->model('records');
    $this->load->library('database');
    (missing quote)

    At step 5:
    When creating controller, it should extend to Controller. Refer to this page: http://codeigniter.com/user_guide/general/controllers.html

  • rahatb

    This is very helpful. Thanks a lot. Thanks to Arnas Risqianto also for drawing attention to some important things. I am new in the Ajax world and was looking for some easy to understand examples on how jQuery ajax and codeigniter works together.

  • rahatb

    This is very helpful. Thanks a lot. Thanks to Arnas Risqianto also for drawing attention to some important things. I am new in the Ajax world and was looking for some easy to understand examples on how jQuery ajax and codeigniter works together.

  • http://www.facebook.com/people/Venkatperfect-Koti/1496171866 Venkatperfect Koti

    thanks

  • http://www.facebook.com/people/Venkatperfect-Koti/1496171866 Venkatperfect Koti

    thanks

  • http://pulse.yahoo.com/_ICJIVMYTNXCRNZJO6ZTXTV4KNE Jason

    I am very weak in JavaScripting. May I know how the final .js and xhtml look like?

  • http://devaldez.com Matt Ryan

    gracias.

  • http://www.facebook.com/mithunpratap.singh Mithunpratap Singh

    We may be interested to invoke a javascript function while clicking these links for doing AJAX style pagination. Still we want to use all other features provided by CodeIgniter’s Pagination class. This can be accomplished simply.

  • http://www.facebook.com/mithunpratap.singh Mithunpratap Singh

    We may be interested to invoke a javascript function while clicking these links for doing AJAX style pagination. Still we want to use all other features provided by CodeIgniter’s Pagination class. This can be accomplished simply.

  • Pingback: Twitted by mryakkie()

  • http://twitter.com/Chris_Ickes Christopher Ickes

    Great tutorial…

    How do we prevent users from accessing the direct url mysite.com/controller/function?

  • http://twitter.com/siopass agung susanto

    thanks, very helpfull…

  • http://twitter.com/siopass agung susanto

    thanks, very helpfull…

  • Pingback: A Quick Code Igniter and JQuery Ajax Tutorial « Sochinda's Blog()

  • http://twitter.com/_bbe Bambang Raharjo

    ini bumbu untuk masak

  • Said Kaldubaev

    looks very nice

  • http://twitter.com/webinone_net webinone

    I also have written and shared here. I will also go on to advance level.

  • http://pulse.yahoo.com/_LTFQCX3RDS4WZP2R2HESNQ255Y 朱建臣

    good resource….

  • Pingback: Top Jquery Links |Avnish Namdev()

  • http://ignivome.com JF

    nice article :) very userful

  • http://univ-lr.fr Pedro

    Nice job !
    I’ll forward this post to my students.
    Thank you

  • noone

    thanks for the post. it was really helpful

  • http://tutjunction.com codeigniter

    nice tutorials

  • http://www.phpff.com fxc86

    good job, thinks!