CI 코드

제목 [팁] 폼검증 경고창으로 띄우기 - jQuery
글쓴이 ci세상 작성시각 2009/10/29 00:16:47
댓글 : 4 추천 : 0 스크랩 : 0 조회수 : 23049   RSS


- 용도 : codeigniter 폼검증 출력을 화면이 아닌 자바스크립트 경고창으로 표현하기

- 편견 : ci를 처음 접하시는 분들이 화면에 출력하는 모습에 대하여 외면하는 현상 발생

- 두마리 토끼 : 폼검증 결과를 화면에도 출력할 수 있고 경고창으로도 출력할 수 있는 개발자 선택

1. 차이점 이미지 설명

<<< ci에서 제공하는 출력형태 >>



<<< ci 폼검증과 + jQuery의 만남을 통하여 익숙한 경고창으로>


2. 설정 : config / constants.php 소스에 아래 소스를 추가
 

// Define Ajax Request
define('IS_AJAX', isset($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest');


3. 컨트롤러 : controllers 폴더에 forms.php 파일을 신규 생성 (utf-8형식으로 생성)
 

<?php

class Forms extends Controller {

 function Forms()
 {
  parent::Controller(); 
 }
 
 function index()
 {
  $this->load->view('form');
 }

 function submit() {

  //load form validation
  $this->load->library('form_validation');

  //set form rules
  $this->form_validation->set_rules('username', '이름을', 'required|min_length[5]|max_length[15]');
  $this->form_validation->set_rules('email', '이메일을', 'required|max_length[20]|min_length[6]|valid_email');

  //run form validation
  $success = $this->form_validation->run();

  //set username variable
  $username = $this->input->post('username');

  //if the validation was a success
  if ((IS_AJAX && $success) || (!IS_AJAX && $success)) { echo "Congradulations {$username}, your form was accepted!"; }

  //if validation failed
  else { echo strip_tags(validation_errors()); }

 }

}




4. 뷰 : views 폴더아래에 form.php 파일을 생성 (utf-8형식으로 생성)


 

<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
	<!-- load jQuery from Google AJAX Libraries API -->
	<script type="text/javascript" src="http://codeigniter-kr.org/include/js/jquery-1.3.2.js"></script>

	<script type="text/javascript">
	$(document).ready(function() {
 		$("form").submit(function(e) {
 			e.preventDefault();
			$.post("/forms/submit", { username: $("#username").val(), email: $("#email").val() }, function (data) {
				alert(data);
			});
 		});
 	});
	</script>

<FORM id=ajax-form action=/forms/submit method=post>
<LABEL for=username>이름</LABEL>
<INPUT id=username name=username>

<LABEL for=email>이메일</LABEL>
<INPUT id=email name=email>
<INPUT id=form_submit type=submit value=확인>
</FORM>


참조 : http://blufusion.net/2009/07/30/easy-ajax-post-with-jquery-and-codeigniter/
첨부파일 form_alert.zip (387.8 KB)
 다음글 [APP] 심플 채팅 소스 (jQuery)
 이전글 [APP] codefight CMS

댓글

변종원(웅파) / 2009/10/29 14:54:01 / 추천 0

폼경고를 alert나 팝업으로 띄우는거 하나 만들려고 생각중이었는데.. ^^

최용운 / 2009/11/07 13:06:21 / 추천 0
굿

배강민 / 2010/04/05 16:51:44 / 추천 0
<?php

	if(validation_errors() !== "")
	{
		?>
		<script language="JavaScript" type="text/javascript">
		//<!--
			alert("<?=str_replace("\n", "\\n", strip_tags(validation_errors()))?>");
		//-->
		</script>
		<?
	}
?>
전.. 일단 간단히 이렇게.... 저 쏼라쏼라를 다 한글로 뿅가리해두신분 계시면 좀 부탁을....
배강민 / 2010/04/05 17:11:17 / 추천 0
아.. 한글팩이 올라와있었군요...ㅋ... 캄사합니당