[egov, ajax] 2개의 ajax, 2개의 submit button 시 생길 수 있는 오류

Sora Kim·2022년 4월 8일
0

작업내용

  • 하나의 jsp로 등록, 상세보기/수정 처리
  • 등록 또는 수정시 서로 다른 버튼 클릭/엔터키

오류내용

  • 등록/수정시 엔터키로 form 전송시 등록ajax와 수정 ajax가 동시에 실행

기존 코드

<script type="text/javaScript">
$(document).ready(function(){

// 등록버튼 클릭
	$('#save').on("click", function(){
		if(!validation()) { // 유효성 체크 
			return false;
		}
		if(confirm("Would you like to save?")) {
			save();
		} 
  });
 // 수정버튼 클릭
 	$('#edit').on("click", function(){
 		if(!validation()) { // 유효성 체크 
			return false;
		}
        //
         '''''''''' (중략)'''''''''''
        //
		if(confirm("Would you like to save with your changes?")) {
			update();
		}
	});
    
    function save() {
	$.ajax({
		type: "post",
		dataType: "json",
		data: $("#form").serialize(),
		url: "<c:url value='/apply/0' />",
		success: function(data) {
			if(data.result == 'ok') {
				alert("saved successfully");
            	document.location.href="/listApply";
			} else {
				alert("error has occurred");
            }
		},
		error: function(error, result){
            alert("error has occurred");
		},
		fail: function(failerr){
			alert("fail to save a form");
		}
	});
}
// update
function update() {
	$.ajax({
		type: "post",
		dataType: "json",
		data: $("#form").serialize(),
		url: "<c:url value='/apply/${appList.id}' />",
		success: function(data) {
			if(data.result == 'ok') {
            	alert("updated successfully");
            	document.location.reload();
			} else {
				alert("error has occurred");
            }
		},
		error: function(error, result){
            alert("error has occurred");		
		},
		fail: function(failerr){
			alert("fail to update a form");
		}
	});
}

jsp form, button

<form id="form" name="form" method="post">
	<input type="text" name="id" id="id" value="${appList.id}">
    <input type="text" name="cont" id="cont" value="${appList.cont}">
</form>	
	<!-- button area -->
	<div>
    	<c:choose>
        	<c:when test="${empty appList}
				<button type="submit" id="save">Save</button>	
             </c:when>
             <c:otherwise>
        		<button type="submit" id="edit">Edit</button>	
             </c:otherwise>
        </c:choose>
			<button type="button" onclick="fnList()">List</button>
	</div>

문제 원인 : submit 버튼이 두개라서 엔터키를 누르면 save, edit의 function이 작동.

<c:choose> 태그를 사용하면 페이지 마다 하나의 submit만 작동할 줄 알았는데 아니였음..ㅠㅠ
(로직을 잘 모르니까 나왔던 실수, 오류 였던 것 같음!)

해결방법 : submit 버튼을 하나로 두고, 제이쿼리나 자바스크립트를 사용해서 이름만 바꿔주면됨...! +

수정코드

<script type="text/javaScript">
$(document).ready(function(){
	
	let listSize =  ${sellDtl.size() };
	/*  controller에서 넘어온 list에 
        내용이 있다..! -> 상세보기/수정화면임 
        없다..! -> 등록하기
    */
	if(listSize > 0) {
		$("#save").text("Edit");
	}
	// 버튼에 적힌 이름이 edit인지 save인지 
	let btnType = $("#save").text();
	
	$('#save').on("click", function(){
		if(!validation()) {
			return false;
		}
		// 저장 save
		if(btnType == "Save") {
			console.log("new-submit");
			if(confirm("Would you like to save?")) {
				save();
			} 
		// 수정 edit
		} else if(btnType == "Edit") {
			console.log("edit");
			if(confirm("Would you like to save your changes?")) {
					update();
			}

	});

})

//
'''' function save/update는 기존 코드와동일하므로 생략 ! ''''''' 
//

jsp form, button

<form id="form" name="form" method="post" onsubmit="return false;">
	<input type="text" name="id" id="id" value="${appList.id}">
    <input type="text" name="cont" id="cont" value="${appList.cont}">
</form>	
	<!-- button area -->
	<div>
    	<button type="submit" id="save">Save</button>	
        <button type="button" onclick="fnList()">List</button>
	</div>

오히려 코드가 간결해지고 보기 편해졌다!

정확한 원인을 몰라서 괜한 controller만 여러번 수정하고 ㅎㅎ

async: false 넣어보고... ajax위치 옮겨보고... ㅠ_ㅠ 다신 반복하지 말자...!

profile
개발잘하고시풔!!!!!!!

0개의 댓글