반응형
PHP + ajax = 로그인 기능
단순히 page 이동으로 로그인 기능을 구현하려면 아래 링크를 참고하시면 됩니다.
2021/01/09 - [php] - [PHP] login, form submit으로 구현하기
login.php 에 form 은 아래와 같이 있습니다.
<form name="mForm" id="mForm">
<input type="text" name="userId" />
<input type="password" name="userPwd" />
<button type="submit">login</button>
</form>
여기서 button type 이 submit 인것을 클릭하면 form 의 내용을 action 으로 전달하게 되어있습니다.
하지만 ajax 로 호출하여 아이디 패스워드를 전달하고 로그인 성공여부만 받아옵니다.
그럼 페이지 이동이 없겠죠.
jQuery ajax 로 요청을 합니다.
$('#mForm button[type=submit]').click(function(e){
e.preventDefault();
let userId = $('#userId').val();
let userPwd = $('#userPwd').val();
$.ajax({
url: './checkLogin.php',
data: {
userId: userId,
userPwd: userPwd
},
type: "POST",
dataType: "json",
success: function(data){
if(data.succ)
alert("로그인 성공");
else
alert("로그인 실패");
},
error: function(err){
alert(err);
}
});
});
받는 페이지는 ./checkLogin.php 입니다. 내용은
<?
header("Content-Type: application/json"); // json 으로 return 할 것이기 때문에
$userId = $_POST["userId"];
$userPwd = $_POST["userPwd"];
// ... userId, userPwd 로 인증
$succ = true;
$userName = "bryan";
$response = array();
$response[0] = array( 'succ' => $succ, 'userName'=> $userName );
echo json_encode($response); // json 형식으로 echo 함.
// 이것 외에 다른 echo 를 하면 안됨.
?>
로그인 체크 요청을 보내고 받는 동안 loading progress 같은 것을 보여주는게 좋겠죠.
$('#mForm button[type=submit]').click(function(e){
e.preventDefault();
// TODO : 시작 전 loading visible
$.ajax({
url: './checkLogin.php',
type: "POST",
dataType: "json",
success: function(data){
// TODO : loading invisible
},
error: function(err){
// TODO : loading invisible
}
});
});
아래와 같은 방법도 있습니다.
// TODO loading 시작
$.ajax.promise({ url : './checkLogin.php', data: param, ... } ).done( function(result, data) {
// 성공일때 내용...
}).fail(function (result, status, responseObj) {
// 실패일때 처리할 내용...
}).always(function (result, status, responseObj) {
// TODO loading 숨김
// 항상 처리할 내용...
});
728x90
반응형
'php' 카테고리의 다른 글
[PHP] mysqli injection #SQL 공격 (0) | 2021.01.09 |
---|---|
[PHP] 비밀번호 처리. password_hash, password_verify (0) | 2021.01.09 |
[PHP] login, form submit으로 구현하기 (0) | 2021.01.09 |
[php] session timeout 설정하기 #$_SESSION 방법 (0) | 2020.12.23 |
[php] session timeout 설정하기 #php.ini 방법 (0) | 2020.12.23 |
댓글