Codeigniter Search AJAX dropdown 예제
이전 예제의 응용으로, dropdown 을 검색할 명칭을 입력하여 fetch 하는 것으로 검색키이를 입력하지 않으면 전체 목록을 dropdown 으로 표시하며, 검색할 명칭을 입력하면 like 로 검색하여 dropdown 을 구현
회원관련 컨트롤러
controller/pilgrims.php
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class Pilgrims extends CI_Controller {
function __construct()
{
// Call the Model constructor
parent::__construct();
$this->load->database();
$query = $this->db->query('set names latin1');
}
public function index()
{
$this->load->library('table');
$this->load->library('pagination');
$this->load->helper('form');
$this->load->model('pilgrims_model');
$data['query'] = $this->pilgrims_model->get_pilgrims();
$this->load->view('pilgrims', $data);
}
public function create()
{
$this->load->helper('form');
$this->load->library('form_validation');
$data['name'] = 'Create a news pilgrim';
$this->form_validation->set_rules('name', 'name', 'required');
$this->form_validation->set_rules('sex', 'sex', 'required');
$this->form_validation->set_rules('birthday', 'bithday', 'required');
$this->form_validation->set_rules('marrige_date', 'marrige_date', 'required');
$this->form_validation->set_rules('phone_no', 'phone_no', 'required');
if ($this->form_validation->run() === FALSE)
{
$this->load->view('pilgrim_create');
}
else
{
$data = array(
'sid' => null,
'name' => $this->input->post('name'),
'sex' => $this->input->post('sex'),
'life_partner' => $this->input->post('life_partner'),
'birthday' => $this->input->post('birthday'),
'marrige_date' => $this->input->post('marrige_date'),
'address' => $this->input->post('address'),
'church_id' => $this->input->post('church_id'),
'pasture' => $this->input->post('pasture'),
'phone_no' => $this->input->post('phone_no'),
'last_update' => date("Y-m-d H:i:s")
);
$this->db->insert('pilgrim_member', $data);
$message['back_url'] = '/index.php/pilgrim';
$this->load->view('success', $message);
}
}
}
?>
"$this->load->view('pilgrim_create');" 에 의해서 입력페이지가 구동됨.
회원정보입력 view
view/pilgrim_create.php
<!DOCTYPE html>
<html lang="ko">
<head>
<?php // <script src="/ajax/libs/jquery/1.9.1/jquery.min.js"></script> ?>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script type="text/javascript">// <![CDATA[
$(document).ready(function() {
$('#church_search').click(function() { //any select change on the dropdown with id country trigger this code
$("#churchs > option").remove(); //first of all clear select items
var church_key = $('#church_text').val(); // here we are taking country id of the selected one.
$.ajax({
type: "POST",
url: "/index.php/churchs/get_name/" + church_key,
success: function(c_result) //we're calling the response json array 'cities'
{
$.each(c_result, function(id, name)
{
var opt = $('<option />'); // here we're creating a new select option with for each city
opt.val(id);
opt.text(name);
$('#churchs').append(opt); //here we will append these new select options to a dropdown with the id 'cities'
});
}
});
});
})
// ]]>
</script>
</head>
<body>
<div id="container">
<h1>Create to PILGRIM.</h1>
<div id="body">
<?php echo validation_errors(); ?>
<?php echo form_open('pilgrim/create') ?>
<label for="name">성명</label>
<input type="input" name="name" /><br />
<label for="sex">성별</label>
<input type="input" name="sex" /> (M:남자, F:여자)<br />
<label for="life_partner">배우자</label>
<input type="input" name="life_partner" /><br />
<label for="birthday">생년월일</label>
<input type="input" name="birthday" /><br />
<label for="marrige_date">결혼기념일</label>
<input type="input" name="marrige_date" /><br />
<label for="address">주소</label>
<input type="input" name="address" /><br />
<label for="church_1">교회</label>
<input type="input" id="church_text" /> <input type="button" id="church_search" value="검색"><br />
<?php $churchs['#'] = 'Please Select'; ?>
<label for="church">Church: </label><?php echo form_dropdown('id', $churchs, '#', 'id="churchs"'); ?><br />
<label for="pasture">목장</label>
<input type="input" name="pasture" /><br />
<label for="phone_no">전화번호</label>
<input type="input" name="phone_no" /><br />
<input type="submit" name="submit" value="Create Pilgrim" />
</form>
</div>
<p class="footer">Page rendered in <strong>{elapsed_time}</strong> seconds</p>
</div>
</body>
</html>
http://192.168.10.213/index.php/pilgrims/create
검색할 명칭을 입력하고, 버튼을 클릭하면 ajax 에 의해서 목록을 가져와 dropdown 으로 표시
model/church.php
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class Churchs extends CI_Controller {
function __construct()
{
// Call the Model constructor
parent::__construct();
$this->load->database();
$query = $this->db->query('set names latin1');
}
public function index()
{
$this->load->library('table');
$this->load->library('pagination');
$this->load->helper('form');
$this->load->model('church_model');
$data['query'] = $this->church_model->get_churchs();
$this->load->view('church', $data);
}
public function get_name($name = null)
{
if ($name == "undefined") $name = null;
$this->load->model('church_model');
header('Content-Type: application/x-json; charset=utf-8');
echo (json_encode($data['query'] = $this->church_model->get_names(urldecode($name))));
}
}
로그파일을 검색했을 때 한글은 urlencode 로 전달된다. 따라서 urldecode 를 적용해야 한다.
192.168.10.113 - - [20/Feb/2014:17:30:14 +0900] "POST /index.php/churchs/get_name/undefined HTTP/1.1" 200 5
192.168.10.113 - - [20/Feb/2014:17:33:37 +0900] "POST /index.php/churchs/get_name/undefined HTTP/1.1" 200 5
192.168.10.113 - - [20/Feb/2014:17:35:45 +0900] "GET /index.php/pilgrims/create HTTP/1.1" 200 4003
192.168.10.113 - - [20/Feb/2014:17:35:57 +0900] "POST /index.php/churchs/get_name/ HTTP/1.1" 200 266
192.168.10.113 - - [20/Feb/2014:17:36:05 +0900] "POST /index.php/churchs/get_name/%EC%A7%80 HTTP/1.1" 200 5
검색인수를 입력하지 않았을 때 호출되는 "undefined" 는 null 로 변경한다.
if ($name == "undefined") $name = null;
DB 스키마
mysql> desc church;
+-------------+----------+------+-----+---------+----------------+
| Field | Type | Null | Key | Default | Extra |
+-------------+----------+------+-----+---------+----------------+
| sid | int(11) | NO | PRI | NULL | auto_increment |
| name | tinytext | NO | | NULL | |
| address | tinytext | YES | | NULL | |
| last_update | datetime | NO | | NULL | |
+-------------+----------+------+-----+---------+----------------+
4 rows in set (0.00 sec)
mysql> select sid,name from church;
+-----+-----------------------+
| sid | name |
+-----+-----------------------+
| 1 | 지구촌교회 |
| 2 | 홍성교회 |
| 3 | 죽전지구촌교회 |
| 4 | 동탄지구촌 |
| 5 | 구리지구촌 |
| 6 | 송파지구촌 |
| 7 | 위례지구촌 |
+-----+-----------------------+
7 rows in set (0.00 sec)
mysql>