Category Archives: codeigniter

CodeIgniter and Ajax Using jQuery tutorial using JSON

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

So now you have created CodeIgniter + AJAX jQuery, you’ll want to use JSON, javascript way to exchange data.

Assuming you already understand how to do CI + AJAX jQuery, using JSON should be pretty easy. We’ll only need to extend couple things. First, we’ll be extending Message::view in Message controller from that tutorial. Then we’ll extend the view to fetch/process the data.

Controller

The previous method was like this:

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);
}

Since we already handled the view type we want to return, all we have to do is add more handler for json. We’ll just convert the array of objects we get from model using json_encode function. Here’s the code:

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 if ($type == 'json') // json, print the output directly
    {
        echo json_encode($data['messages']);
    }

    else // load the default view
        $this->load->view('default', $data);
}

View

We’ll be adding a button to trigger the new “fetch json data” so the previous handling is still functional.

The previous view (default.php) was:

load->view(‘messages_list’) ?>

Then we added second submit button:

load->view(‘messages_list’) ?>

Now the javacript. The previous javascript/jquery code was:

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

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

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

Then we need to create handler to fetch the data (in json) and put it in correct html tag. Here’s the code after we added handler for second submit button:

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

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

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

    $('#submit2').click(function() {
        var msg = $('#message').val();
        $('#message').val('');
        $.post("", {message: msg}, function() {
            $.getJSON("", function(data) {
                var contentHtml = "
    “; $(data).each(function(index, item) { contentHtml += ”

  1. “; contentHtml += item.message; contentHtml += “
  2. “; }); contentHtml += “

";
                $('#content').html(contentHtml);
            });
        });
    });
});

It’s done. Try yourself, or download the files needed.

I know, it’s pretty basic. But I think it’s enough to get you started to use json in exchanging data. Why json instead of complete html? less data transfer.

Advertisements
Tagged , , , ,

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 , , , ,