jigniter™

jQuery & CodeIgniter – Perfect combination for web application

CodeIgniter and AJAX using jQuery

sin comentarios

jQuery has some interesting functions that allows you to add AJAX support easily.

If you are new on CodeIgniter, we’d recommend to check out the user guide. If you are new on jQuery, you can check the AJAX documentation.

The problem

You have a page that need to communicate with a controller function using an AJAX way. The CodeIgniter controller function returns an JSON or plain result.

For example, suppose we are building a time tracker tool based on a web clock. We want users (freelancers or employees) to clock in and clock out without leaving the page or refreshing the browser. So, an AJAX behavior will be nice when the user click on a Clock In and/or Out button.

The solution

Prepare a simple view and add a button or link:

<a href="#" class="round button clock" rel="next" id="timebutton">Clock In</a>

Prepare the controller to accept and respond results. To achieve that, I will create a new controller named Time and place the following function:

function ajax_clock()
{
    // function code goes here
    // and return results in json format
}

So, at our client side, we will execute AJAX calls to run this controller function.

What should we add to that function? Basically we want that each time the user clicks on the button, a new entry is logged into the database to tell the application that someone has been clocked in or out.

For that purpose, let’s create a time_model CodeIgniter model that encapsulates the communication between controller and database.

function clockit()
{
    // clockit() model function goes here
    // and return last state
}

Escrito por admin

2009-07-10 at 2:02 pm

Publicado en Uncategorized

Tags:

Leave a Reply