Codeigniter jquery-AJAX 예제
Codeigniter 에서 ajax 를 구동하는 것은 여러예제가 있으나, 가장 많이 사용되는 부분은 dropdown 예제임. 본 예제는 국가를 선택하고, 도시를 선택하는 예제임. 유명한 예제이기는 하지만, 몇가지 오타가 있어서 처음 설치시 제대로 동작하지 않는 부분들이 있어서, 실제 겸험으로 다시 올리는 것임.
controller/user.php
<?php
class User extends CI_Controller {
public function __construct() {
parent::__construct();
$this->load->helper('form');
$this->load->model('country_model');
}
public function index() {
$this->load->view('user');
}
public function register() {
$data['countries'] = $this->country_model->get_countries();
$this->load->view('post_view', $data);
}
public function get_cities($country) {
$this->load->model('city_model');
header('Content-Type: application/x-json; charset=utf-8');
echo(json_encode($this->city_model->get_cities($country)));
}
}
몇가지 유의해야 할 부분
public function __construct() {
parent::__construct();
$this->load->helper('form');
$this->load->model('country_model');
생성자에 form 헬퍼와 country_model (model/country_model.php) 를 선언한다. form 헬퍼는 view/register.php 에서 사용하는 dropdown() 이 선언 되어 있으며, country_model 은 국가를 loading 하고, 국가를 선택했을 때, 도시명을 load 하는 모델러 이다.
public function register() {
$data['countries'] = $this->country_model->get_countries();
$this->load->view('post_view', $data);
}
"$this->country_model->get_countries();" 에서 국가 row 를 loading 하여, $data 에 할당해서, view 를 호출한다. get_countries() 는 countries 테이블 전체를 fetch 하는 것을 의미한다.
model/city_model.php
<?php
class City_model extends CI_Model {
public function __construct() {
$this->load->database();
}
function get_cities($country = null) {
$this->db->select('id, city_name');
if ($country != NULL) {
$this->db->where('country_id', $country);
}
$query = $this->db->get('cities');
$cities = array();
if ($query->result()) {
foreach ($query->result() as $city) {
$cities[$city->id] = $city->city_name;
}
return $cities;
} else {
return FALSE;
}
}
}
?>
view/register.php
<html>
<head>
<script src="/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script type="text/javascript">// <![CDATA[
$(document).ready(function() {
$('#country').change(function() { //any select change on the dropdown with id country trigger this code
$("#cities > option").remove(); //first of all clear select items
var country_id = $('#country').val(); // here we are taking country id of the selected one.
$.ajax({
type: "POST",
url: "/index.php/user/get_cities/" + country_id, //here we are calling our user controller and get_cities method with the country_id
success: function(cities) //we're calling the response json array 'cities'
{
$.each(cities, function(id, city) //here we're doing a foeach loop round each city with id as the key and city as the value
{
var opt = $('<option />'); // here we're creating a new select option with for each city
opt.val(id);
opt.text(city);
$('#cities').append(opt); //here we will append these new select options to a dropdown with the id 'cities'
});
}
});
});
});
// ]]>
</script>
</head>
<body>
<?php $countries['#'] = 'Please Select'; ?>
<label for="country">Country: </label><?php echo form_dropdown('country_id', $countries, '#', 'id="country"'); ?><br />
<?php $cities['#'] = 'Please Select'; ?>
<label for="city">City: </label><?php echo form_dropdown('city_id', $cities, '#', 'id="cities"'); ?><br />
</body>
</html>
ajax script "/ajax/libs/jquery/1.9.1/jquery.min.js" 는 복사해 놓아야 함. (또는 인터넷 원격지에서 들어오는 것을 그대로 유지시키거나)
dropdown() 에서 나라가 선택되게 되면, "/index.php/user/get_cities/" + country_id" 의 URL 로 controller/user.php 의 get_cities() function 을 호출하게 되며, 이것은 city_model 을 호출하여, city_model->get_cites() 를 호출하여, 해당 결과를 json 로 encoding 하여 리턴, ajax 에서 select 의 optins 으로 추가된다.
success: function(cities) //we're calling the response json array 'cities'
{
$.each(cities, function(id, city) //here we're doing a foeach loop round each city with id as the key and city as the value
{
var opt = $('<option />'); // here we're creating a new select option with for each city
opt.val(id);
opt.text(city);
$('#cities').append(opt); //here we will append these new select options to a dropdown with the id 'cities'
});
데이터베이스 설정
mysql> desc countries;
+--------------+----------+------+-----+---------+-------+
| Field | Type | Null | Key | Default | Extra |
+--------------+----------+------+-----+---------+-------+
| id | int(11) | NO | | NULL | |
| country_name | tinytext | NO | | NULL | |
+--------------+----------+------+-----+---------+-------+
2 rows in set (0.00 sec)
mysql> desc cities;
+------------+----------+------+-----+---------+-------+
| Field | Type | Null | Key | Default | Extra |
+------------+----------+------+-----+---------+-------+
| id | int(11) | NO | | NULL | |
| country_id | int(11) | NO | | NULL | |
| city_name | tinytext | NO | | NULL | |
+------------+----------+------+-----+---------+-------+
3 rows in set (0.00 sec)
mysql> select * from countires;
ERROR 1146 (42S02): Table 'GFMC.countires' doesn't exist
mysql> select * from countries;
+----+--------------+
| id | country_name |
+----+--------------+
| 1 | korea |
| 2 | usa |
+----+--------------+
2 rows in set (0.00 sec)
mysql> select * from cities;
+----+------------+-----------+
| id | country_id | city_name |
+----+------------+-----------+
| 1 | 1 | seoul |
| 2 | 1 | busan |
| 3 | 2 | LA |
| 4 | 2 | NY |
+----+------------+-----------+
4 rows in set (0.00 sec)
mysql>
실행화면
access 로그 확인
ajax 가 호출되는것을 확인하기 쉽지 않는데, access.log 를 조회해 보면, 그래도 적어도 스크립트에러로 구동되지 않는 것은 확인할 수 있다.
192.168.10.113 - - [20/Feb/2014:09:11:17 +0900] "POST /index.php/user/get_cities/1 HTTP/1.1" 500 1370
192.168.10.113 - - [20/Feb/2014:09:13:11 +0900] "GET /index.php/user/register HTTP/1.1" 200 2022
192.168.10.113 - - [20/Feb/2014:10:36:04 +0900] "GET /index.php/user/register HTTP/1.1" 200 2022
192.168.10.113 - - [20/Feb/2014:10:36:07 +0900] "POST /index.php/user/get_cities/1 HTTP/1.1" 500 1370
192.168.10.113 - - [20/Feb/2014:10:38:16 +0900] "GET /index.php/user/register HTTP/1.1" 200 2022
192.168.10.113 - - [20/Feb/2014:10:38:19 +0900] "POST /index.php/user/get_cities/1 HTTP/1.1" 500 1362
192.168.10.113 - - [20/Feb/2014:10:44:54 +0900] "GET /index.php/user/register HTTP/1.1" 200 2022
192.168.10.113 - - [20/Feb/2014:10:44:57 +0900] "POST /index.php/user/get_cities/1 HTTP/1.1" 200 45
192.168.10.113 - - [20/Feb/2014:10:45:39 +0900] "GET /index.php/user/register HTTP/1.1" 200 2022
192.168.10.113 - - [20/Feb/2014:10:45:41 +0900] "POST /index.php/user/get_cities/1 HTTP/1.1" 200 27
192.168.10.113 - - [20/Feb/2014:11:08:21 +0900] "GET /index.php/user/register HTTP/1.1" 200 2022
192.168.10.113 - - [20/Feb/2014:11:08:26 +0900] "POST /index.php/user/get_cities/1 HTTP/1.1" 200 27
192.168.10.113 - - [20/Feb/2014:11:26:55 +0900] "POST /index.php/user/get_cities/2 HTTP/1.1" 200 21
192.168.10.113 - - [20/Feb/2014:13:22:12 +0900] "GET /index.php/user/register HTTP/1.1" 200 2013