Thursday, December 5, 2013

How To Use Ajax with jQuery and CodeIgniter Tutorial?

You can easily use ajax with jQuery and Codeigniter. Below is the tutorial with complete source code on how to use ajax with jQuery and Codeigniter.

Controller : ajax_sample.php
class Ajax_sample extends CI_Controller {
    function __construct(){
     * show list as a table, get data from "test_model"
     * */
    function get_list_view(){
        $data = array();
        $data['title'] = 'Lorem ipsum';
        $data['list'] = $this->test_model->get_data();
        $this->load->view('sample_table', $data);
    function index(){
Model : test_model.php
//file: application/models/test_model.php

class Test_model extends CI_Model {
    function __construct(){
    function get_data(){
        $type = $this->input->post('type');
        if($type != 1){
            return array();
        return array(
                'name' => 'Abigail',
                'email' => '',
                'registered_date' => '01/17/2014'
                'name' => 'Ralph',
                'email' => '',
                'registered_date' => '10/08/2013'
Views: test_page.php
<title>Ajax sample (with CodeIgniter)</title> <script src="//"></script>
 <script type="text/javascript">
 var controller = 'ajax_sample';
 var base_url = '<?php echo site_url(); //you have to load the "url_helper" to use this function ?>';

function load_data_ajax(type){

 'url' : base_url + '/' + controller + '/get_list_view',
 'type' : 'POST', //the way you want to send data to your URL
 'data' : {'type' : type},
 'success' : function(data){ //probably this request will return anything, it'll be put in var "data"

var container = $('#container'); //jquery selector (get element by id)

 <button onclick="load_data_ajax(1)">Load list (type 1)</button>
 <button onclick="load_data_ajax(2)">Load list (type 2)</button>

 <hr />

 <div id="container">
Views: sample_table.php

<?php if(isset($title) && !empty($title)) : ?>
    <h1><?php echo $title; ?></h1>
<?php endif; ?>

<?php if(isset($list) && count($list)) : ?>
             <th>Registered date</th>
            <?php foreach($list as $row) : ?>
                    <td><?php echo $row['name']; ?></td>
                    <td><?php echo $row['email']; ?></td>
                    <td><?php echo $row['registered_date']; ?></td>
            <?php endforeach; ?>
<?php else : ?>
    <h3>No results found!</h3>
<?php endif; ?>


1 comment:

  1. It is amazing and wonderful to visit your site.Thanks for sharing this information,this is useful to me...
    Android Training in Chennai
    Ios Training in Chennai