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.

Tagged , , , ,

7 thoughts on “CodeIgniter and Ajax Using jQuery tutorial using JSON

  1. […] Need how to do this using JSON? Check CodeIgniter and Ajax Using jQuery tutorial using JSON. — May 27, 2008 10:28 pm · ajax, ci, codeigniter, jquery, tutorial · […]

  2. Lenouvdu44 says:

    Hi
    Sorry for my english, i’m a newbie in english like in codeigniter ^^
    thx for this tuto … but it doesn’t work on CI 2, does it ?

    I have just copied your files and changed some keywords for compatibilty with 2.0, loaded javascript library for Jquery in my controller and changed URI in default view. And i’ve imported your sql script in my db.

    I understand your script, except the part on javascript’s function … lol. I didn’t study ajax & javascript.

    can you help me or can you give me some help links ? thx. It’s already quite difficult for a frenchi to find help on CI 2.0, ajax … and more in frenchūüėÄ

    bye

  3. Sachinkrishna says:

    hey…possibility of hacking..ryt ?

  4. Anonymous says:

    For more versatility you can load views into an array and then output that array as the json object by utilizing the optional third parameter of the load-.view() function, this parameter if set to true tells so return the output of the view rather then sending it to the output handler.

    /* PHP Controller file */
    ie:
    else if ($type == ‘json’) // json, print the output directly
    { $data[‘data’] = “some data for the view!”;¬† ¬† ¬† ¬† ¬† ¬† ¬† ¬†¬†$json[‘view1’] = $this->load->view(‘view1’,$data,TRUE);¬†
    ¬† ¬† ¬† ¬† ¬† ¬† ¬† ¬†¬†$json[‘view2’] = $this->load->view(‘view2’,$data,TRUE);¬†
    echo json_encode($json);
    }
    And then on the php view that called the json object you can put this under your on complete function within the post call:

    $(‘#submit2’).click(function() {
    var msg = $(‘#message’).val();
    $(‘#message’).val(”);
    $.post(“”, {message: msg}, function(data) { $.(“.view1”).html=(data.view1); /*load your view1 output into some element with a class name of view1*/ $.(“.view2”).html=(data.view2); /*load your view2 output into some element with a class name of view2*/
    }), ‘json’;/*This is important – it lets the function know the input is json*/
    });Doing it this way would effectively let use codeigniter to process the output still and let you modifier different parts of the document with ease.

  5. anonymus says:

    vxcvxv

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: