Ajax with Active Record in CodeIgniter Framework


Create new database named learn_codeigniter_with_real_apps. This database have 1 table: Product table.

--
-- Table structure for table `product`
--

CREATE TABLE `product` (
  `id` int(11) NOT NULL PRIMARY KEY AUTO_INCREMENT,
  `name` varchar(250) NOT NULL,
  `price` double NOT NULL,
  `quantity` int(11) NOT NULL,
  `description` text NOT NULL,
  `status` tinyint(1) NOT NULL,
  `photo` varchar(250) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;

--
-- Dumping data for table `product`
--

INSERT INTO `product` (`name`, `price`, `quantity`, `description`, `status`, `photo) VALUES('name 1', 2, 5, 'Description 1', 0, 'thumb1.gif');
INSERT INTO `product` (`name`, `price`, `quantity`, `description`, `status`, `photo) VALUES('name 2', 7, 3, 'Description 2', 1, 'thumb2.gif');
INSERT INTO `product` (`name`, `price`, `quantity`, `description`, `status`, `photo) VALUES('name 3', 2, 7, 'Description 3', 1, 'thumb3.gif');
INSERT INTO `product` (`name`, `price`, `quantity`, `description`, `status`, `photo) VALUES('name 4', 3, 8, 'Description 4', 1, 'thumb1.gif');
INSERT INTO `product` (`name`, `price`, `quantity`, `description`, `status`, `photo) VALUES('name 5', 8, 2, 'Description 5', 1, 'thumb2.gif');
INSERT INTO `product` (`name`, `price`, `quantity`, `description`, `status`, `photo) VALUES('name 6', 9, 11, 'Description 6', 1, 'thumb3.gif');

Structure of Product Table

Data of Product Table




Create new folder named assets in root project. In this folder, create new folders as below:

Create new folder named images in assets folder. Copy images need to use in project to images folder.

In CodeIgniter Project, Open config.php file in config folder. Set value for base_url config as below:

$config['base_url'] = 'http://localhost:9092/LearnCodeIgniterWithRealApps/';

In CodeIgniter Project, Open autoload.php file in config folder. Add database library to libraries config as below:

$autoload['libraries'] = array('database');

In CodeIgniter Project, Open autoload.php file in config folder. Add url helper to helper config as below:

$autoload['helper'] = array('url');

In CodeIgniter Project, Open database.php file in config folder. Add values as below connect to database:

$db['default'] = array(
	'hostname' => 'localhost',
	'username' => 'root',
	'password' => '123456',
	'database' => 'learn_codeigniter_with_real_apps'
);




Create new PHP file named product_model.php in models folder as below:

<?php
if (! defined('BASEPATH'))
    exit('No direct script access allowed');

class Product_model extends CI_Model
{

    function findAll()
    {
        return $this->db->get('product')->result();
    }

    function find($id)
    {
        return $this->db->where('id', $id)
                        ->get('product')
                        ->row();
    }

}

In CodeIgniter Project, Open autoload.php file in config folder and set value for model config as below:

$autoload['model'] = array('product_model' => 'productModel');

Create new PHP file named demo.php in controllers folder as below:

<?php
defined('BASEPATH') or exit('No direct script access allowed');

class Demo extends CI_Controller
{

    public function index()
    {
        $this->load->view('demo/index');
    }

    public function demo1()
    {
        echo 'Hello World';
    }

    public function demo2()
    {
        echo $_POST['a'] + $_POST['b'];
    }

    public function demo3()
    {
        echo json_encode($this->productModel->find(2));
    }

    public function demo4()
    {
        echo json_encode($this->productModel->findAll());
    }
}

Open routes.php file in config folder. Set value for default_controller as below:

$route['default_controller'] = 'demo';




Create new folder named demo in views folder. In this folder, create new views as below:

Create new PHP file named index.php. In this file use Ajax of JQuery Library as below:

<?php defined('BASEPATH') or exit('No direct script access allowed'); ?>
<html>
	<head>
		<title>Autocomplete</title>
    	<script src="https://code.jquery.com/jquery-1.10.2.js"></script>
    	<script type="text/javascript">
          	$(document).ready(function(){
            	$('#button1').click(function(){
            		$.ajax({
            			type:'GET',
            			url:'<?php echo site_url('demo/demo1'); ?>',
            			success:function(result){
            				$('#result').html(result);
            			}
            		});
            	});

            	$('#button2').click(function(){
            		$.ajax({
            			type:'POST',
            			data:{a:1,b:2},
            			url:'<?php echo site_url('demo/demo2'); ?>',
            			success:function(result){
            				$('#result').html(result);
            			}
            		});
            	});

            	$('#button3').click(function(){
            		$.ajax({
            			type:'GET',
            			url:'<?php echo site_url('demo/demo3'); ?>',
            			success:function(result){
            				var product = $.parseJSON(result);
            				var s = 'Id: ' + product.id;
            				s += '<br>Name: ' + product.name;
            				s += '<br>Price: ' + product.price;
            				$('#result').html(s);
            			}
            		});
            	});

            	$('#button4').click(function(){
            		$.ajax({
            			type:'GET',
            			url:'<?php echo site_url('demo/demo4'); ?>',
            			success:function(result){
            				var listProducts = $.parseJSON(result);
            				var s = '';
            				for(var i=0; i<listProducts.length; i++){
            					s += '<br>Id: ' + listProducts[i].id;
            					s += '<br>Name: ' + listProducts[i].name;
            					s += '<br>Price: ' + listProducts[i].price;
            					s += '<br>===============';
            				}
            				$('#result').html(s);
            			}
            		});
            	});

            });
        </script>
	</head>
	<body>

		<form>
            <input type="button" value="Hello" id="button1">
            <input type="button" value="Sum" id="button2">
            <input type="button" value="Json" id="button3">
            <input type="button" value="List Object with Json" id="button4">
            <br>
            <div id="result"></div>
        </form>

	</body>
</html>




Access index action in Demo controller with following url: http://localhost:9092/LearnCodeIgniterWithRealApps/demo/index

Output

I recommend you refer to the books below to learn more about the knowledge in this article: