CodeIgniter Laravel PHP Example Javascript jQuery MORE Videos New

How to Retrieve data using CodeIgniter, Ajax


We use 3 file for retrieve students data.

  1. Crud.php Path: application\controllers\Crud.php
  2. Crud_model.php Path: application\models\Crud_model.php
  3. view.php Path: application\views\view.php

Sql Table

CREATE TABLE crud (
  `id` int(11) NOT NULL,
  `first_name` varchar(30) NOT NULL,
  `last_name` varchar(30) NOT NULL,
  `email` varchar(30) NOT NULL,
   PRIMARY KEY (id)
);

view.php(View)

<!DOCTYPE html>
<html lang="en">
<head>
  <title>View Ajax</title>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css">
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js"></script>
  <script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js"></script>
</head>
<body>
<div class="container">
  <h2>View data</h2>
	<table class="table table-bordered table-sm" >
    <thead>
      <tr>
		<th>Sl No</th>
        <th>Name</th>
        <th>Email</th>
        <th>Phone</th>
		<th>City</th>
      </tr>
    </thead>
    <tbody id="table">
      
    </tbody>
  </table>
</div>
<script>
	$.ajax({
		url: "<?php echo base_url("Crud/viewajax");?>",
		type: "POST",
		cache: false,
		success: function(data){
			//alert(data);
			$('#table').html(data); 
		}
	});
</script>
</body>
</html>

Crud.php(Controller)

<?php
class Crud extends CI_Controller 
{
	public function __construct()
	{
		parent::__construct();
		$this->load->helper('url'); 
		$this->load->database();
		$this->load->model('Crud_model');
	}
	public function view()
	{
		$this->load->view('view');
	}
	
	public function viewajax()
	{
				$data=$this->Crud_model->display_records();
				$i=1;
				foreach($data as $row)
				{
					  echo "<tr>";
					  echo "<td>".$i."</td>";
					  echo "<td>".$row->name."</td>";
					  echo "<td>".$row->email."</td>";
					  echo "<td>".$row->phone."</td>";
					  echo "<td>".$row->city."</td>";
					  echo "</tr>";
					  $i++;
				}
	}
}

Crud_model.php(Model)

<?php
class Crud_model extends CI_Model 
{
	function display_records()
	{
		$query=$this->db->query("select * from crud");
		return $query->result();
	}
}

Now run the program on your browser with the below URL:

http://localhost/codeIgniter/Crud/view

After fetch data the table look like this.

Id first name last name Email Id
1 Divyasundar Sahu divyasundar@gmail.com
2 Hritika Sahu hritika@gmail.com
3 Milan Jena milanjena@gmail.com