CI 묻고 답하기

제목 php codeigniter 에서 redirect와 javascript 실행 중 발생한 문제입니다.
글쓴이 overman623 작성시각 2016/02/22 17:20:44
댓글 : 8 추천 : 0 스크랩 : 0 조회수 : 14735   RSS

codeigniter을 독학하는 초보자입니다.

ajax를 이용한 모달로그인을 구현 중인데, 어려움을 겪고 있습니다.

코드 입니다.

<?php

defined('BASEPATH') OR exit('No direct script access allowed');

 

Class Userauth extends MY_Controller{

    

    function __construct(){

        parent::__construct();

        $this->load->model('userauth_m');

        $this->load->library('form_validation');

        $this->load->helper('url');

    }

    

    function userRegister($input){

        return $this->userauth_m->register(

            array(

                'username' => $input->post('username', TRUE),

                'password' => $input->post('password', TRUE),

                'name' => $input->post('name', TRUE),

                'email' => $input->post('email', TRUE),

                'reg_date' => $input->post('reg_date', TRUE)

            ));

    }

    

    function joinHandler(){

        $this->load->view('header_v');

        if ($_POST) { $this->userRegister($this->input); $this->load->view('home'); }

        else $this->load->view('navigation/auth/join_v');

        $this->load->view('footer_v');

    }

 

    

    function formValidationCheck($input){

        $input->set_rules('login_username','아이디','required|alpha_numeric');

        $input->set_rules('login_password','비밀번호','required');

        $result = $this->form_validation->run();

        return $result;

    }

 

    function makeAuthData($inputData){

        $auth_data = array(

            'username' => $inputData->post('login_username', TRUE),

            'password' => $inputData->post('login_password', TRUE)

        );

        return $auth_data;

    }

 

    function makeSessionData($result){

        $sessionData = array(

            'username' => $result->username,

            'email' => $result->email,

            'logged_in' => TRUE

            );

        return $result;

    }

 

    function SessionDataSetAfterloginCheck($authData){

        $result = $this->userauth_m->loginCheck($authData);

        if ($result) {

            $sessionData = $this->makeSessionData($result);

            $this->session->set_userdata($authData['username'], $sessionData);

            echo 'aa';   //view 에 input_again 이라는 아이디를 가진 태그에 찍힌다.

            redirect('http://localhost/kim/main');

            //Header("Location:http://localhost/kim/main");

            //parent.location.href('http://localhost/kim/main');

 

        } else echo 'password is not collect';

    }

 

    function noticeBlank($authData){

        if (!trim($authData['username'])) echo 'insert id';

        else if (!trim($authData['password'])) echo 'insert password';

    }

 

    function login(){

        $this->refreshHome();

        if ($this->formValidationCheck($this->form_validation)) {

            $authData = $this->makeAuthData($this->input);

            $this->SessionDataSetAfterloginCheck($authData);

        } else $this->noticeBlank($this->makeAuthData($this->input));

        exit;

    }

 

    function logout(){

        $this->session->sess_destroy();

        echo '<meta http-equiv="Content-Type" context="text/html; charset=utf-8" />';

        alert1('로그아웃 되었습니다.', '/kim/main/home');

        exit;

    }

 

}

?>

 


SessionDataSetAfterloginCheck() 

메소드를 보면 아이디 패스워가 일치했을 때 세션에 데이터를 저장하고 해당하는 경로에 리다이렉션을 하고 싶었습니다.

하지만 나온 결과는 해당하는 프레임안에 이렇게 나오는 현상이 발생했습니다.

 

그래서 해결하려고 자바 스크립트를 실행시켜서 경로 이동을 하려했지만

해당하는 자바스크립트 구문만 찍히고 실행이 되지 않았습니다.

유독 이 메소드 안에서만 자바스크립트 실행과 라다이렉션이 안되었습니다.

이상한점은 다른 메소드에서는 자바스크립트 실행이 정상적으로 됐습니다.

보시는 분들께서 실마리라도 주신다면 좋겠습니다.

혹시라도 답변을 위해 다른 부분의 코드가 필요하다면 올리겠습니다.

 

 

 

 

 다음글 초보입니다. date관련 질문드립니다. (1)
 이전글 addslashes 로 디비 사용하기 (1)

댓글

taegon / 2016/02/22 17:59:22 / 추천 0

로그인 화면에서 "로그인 버튼"을 클릭하면 ajax로 서버에 보내는 형태죠?

그렇다면 ajax의 결과값을 받아서 로그인 성공인지 실패인지 확인 후에 location.href로 이동시키는게 맞습니다.

submit으로 했다면야 리다이렉트로 하면 되겠지만 ajax는 실행하고 해당 결과값을 가져오도록 되어 있는데 그대로 출력하신듯 하네요.

overman623 / 2016/02/22 18:05:19 / 추천 0

답변주셔서 감사합니다.

맞습니다. ajax로 전송하는 형태이고 출력을 그대로 할 의도는 아니었습니다.

출력을 했을때 그러니까 SessionDataSetAfterloginCheck() 메소드에 주석되어 있는부분

세션에 저장을 한후에 그 다음줄을

               echo "
            <script>
            location.href='/kim/main';
            //alret('aaaa');
            </script>
        ";

이렇게 작성해도 스크립트문 그대로 출력이 되었다는게 문제였습니다. 주석되어있는 alert를 풀어도 alert가 실행되지 않았습니다.

원인을 도무지 찾을수 없었습니다.

taegon / 2016/02/23 10:39:48 / 추천 0

무슨 문제인지 확인하시려면 로그인 시 사용하는 스크립트를 올려주세요.

해당 부분을 보면 왜 저렇게 나오는지 설명드릴 수 있을것 같습니다.

overman623 / 2016/02/23 15:05:32 / 추천 0

<script>

    function getXMLHttpRequest(){
        if (window.ActiveXObject) {
            try { 
                return new ActiveXObject('Msxml2.XMLHTTP');
            } catch(e) {
                try { return new ActiveXObject('Microsoft.XMLHTTP');
                } catch(e1) { return null; }
            }
        } else if (window.XMLHttpRequest) return new XMLHttpRequest();
        else return null;
    }

    var httpRequest = null;

    function sendRequest(url, params, callback, method) {
        httpRequest = getXMLHttpRequest();
        var httpMethod = method ? method : 'GET';
        if (httpMethod != 'GET' && httpMethod != 'POST') {
            httpMethod = 'GET';
        }
        var httpParams = (params == null || params == '') ? null : params;
        var httpUrl = url;
        if (httpMethod == 'GET' && httpParams != null) {
            httpUrl = httpUrl + '?' + httpParams;
        }
        httpRequest.open(httpMethod, httpUrl, true);
        httpRequest.onreadystatechange = callback;
        httpRequest.setRequestHeader("Content-Type","application/x-www-form-urlencoded;charset=UTF-8");
        httpRequest.setRequestHeader("Cache-Control","no-cache, must-revalidate");
        httpRequest.setRequestHeader("Pragma","no-cache");
        httpRequest.send(httpMethod == 'POST' ? httpParams : null);
    }

    function callback_hello(){
        if (httpRequest.readyState == 4 && httpRequest.status == 200) {
            var contents = document.getElementById('input_again');
            if (httpRequest.responseText == 'SUCCESS') location.href='/kim/main/';
            else contents.innerHTML = httpRequest.responseText;
        }
    }

    function serverRequest(){
        var name = 'login_username='+encodeURIComponent(document.getElementById('login_username').value)
        +'&login_password='+encodeURIComponent(document.getElementById('login_password').value);
        sendRequest("/kim/userauth/login", name, callback_hello, "POST");
    }

</script>

--------------------------가 스크립트 코드이고

혹시 몰라서 로그인 모달부분의 html 태그를 같이 올립니다. 부트스트랩 모달을 사용했습니다. ------------

    <div class="modal fade" id="myModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel">
      <div class="modal-dialog" role="document">
        <div class="modal-content" id="modal-content">
          <div class="modal-header">
            <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">×</span></button>
            <h4 class="modal-title" id="myModalLabel">Login Form</h4>
          </div>
          <div class="modal-body">
            <form id="form-group">
              <div id="input-group">
                <input type="text" id="login_username" name="login_username" placeholder="id" class="form-control input-md">
                <input type="password" id="login_password" name="login_password" placeholder="password" class="form-control input-md">
                <strong id="input_again"></strong>
              </div>
              <div id="button-group">
                <button type="button" class="btn btn-primary" onclick="serverRequest()">Login</button>
              </div>
            </form>
          </div>      
        </div>
      </div>
    </div>

taegon / 2016/02/24 01:52:49 / 추천 0

일단 답변을 드리자면

  function callback_hello(){
        if (httpRequest.readyState == 4 && httpRequest.status == 200) {
            var contents = document.getElementById('input_again');
            if (httpRequest.responseText == 'SUCCESS') location.href='/kim/main/';
            else contents.innerHTML = httpRequest.responseText;
        }
    }

위의 ajax의 callback 함수에 답이 있네요. 서버의 SessionDataSetAfterloginCheck를 정상적으로 실행하고 

응답을 받은 결과값이 SUCCESS인 경우 location.href='/kim/main/';을 실행하도록 스크립트가 작성되어 있네요.

서버의 SessionDataSetAfterloginCheck 함수에 로그인이 성공하고 나면 echo로 SUCCESS를 출력하면 됩니다.

한가지 의문점은 이 코드를 직접 다른 소스를 보고 참고해서 직접 작성하신 건가요?

기본적인 ajax의 동작방법만 알면 오류가 무엇인지 알고 해결하실 수 있는 문제입니다. 

overman623 / 2016/02/24 11:07:34 / 추천 0

코드를 다른데에서 참고하지 않았습니다. php 메소드 안에서 location.href 이런식으로 이동하는 자바스크립트 코드 작성을 포기했었습니다. 그래서 echo로 SUCCESS를 출력할때 해당하는 조건을 실행하도록 했었고 그 이후의 코드를 복사붙여넣기 한 것입니다. 이런식의 해결방법도 있지만 컨트롤러의 메소드인 SessionDataSetAfterloginCheck()에서 location.href 같은 자바스크립트구문을 제대로 실행할수 있는 방법은 없는지요?

taegon / 2016/02/24 15:08:49 / 추천 0

컨트롤러에서 이동까지 처리하고 싶으시다면 submit을 이용하셔서 처리하셔야 합니다. ajax로는 실행 후 해당 결과값을 받아오기 때문에 header든 스크립트를 이용한 location.href든 실행 후 결과를 출력합니다. 해당 페이지는 아무런 상관이 없는거죠.

overman623 / 2016/02/26 18:52:26 / 추천 0
정말 감사합니다. 저에게 큰 도움이 되었습니다.