2017-12-26 10 views
-1

나는 현재 AJAX를 잘 모른다. AJAX로 JavaScript에서 PHP 파일을 호출 한 후 부울 값을 반환 할 수 있는지 알고 싶습니다.PHP로 아약스로 부울 반환

더 자세히 설명하면 코드를 설명합니다.

페이지 만 2 단계로 로그인합니다. 먼저 사용자는 이메일 주소를 입력해야합니다. 이 데이터베이스에있는 경우 사용자는 새 페이지를로드하지 않고 비밀번호를 입력해야합니다. 암호가 좋은 경우, 그는 성공적으로 로그인 한

를 그래서 나는 아직 (메일 <input type="email" name="email" onsubmit="mailCheck(this.value)">에서 오는 문자열) 작성하지 않은 메일 제출시라는 기능이 있습니다.

function mailCheck(mail) { 
    for (i = 0; i < mail.length; i++) { 
     if (mail[i] == "") { 
      document.getElementById("input").style.background = "#FFDDEE"; 
     } 
    } 
    if (!existing(mail)) { 
     document.getElementById("input").style.background = "#FFDDEE"; 
    } else { 
     //TODO: GO TO NEXT STEP (PASSWORD) 
    } 
} 
function existing(mail) { 
    var xmlhttp = new XMLHttpRequest(); 
    //TODO: USE mailCheck.php 
    return false; 
} 

그래서 여기서는 메일이 데이터베이스에서 발견되었는지를 어떻게 알 수 있는지에 초점을 맞추고 있습니다. 그래서 내 파일 mailCheck.php에는 다음이 포함

<?php 
session_start(); 
$mail = htmlspecialchars($_POST['mail']); 
$page = htmlspecialchars($_GET['reply']); 

//Connect to the database (done) 
//Ask the database (done) 

//Act according to the answer of the database 
if (!$result) { 
     //TODO: RETURN FALSE WITH AJAX 
} else { 
     $_SESSION['ID'] = $result['ID']; 
     //Others variables (done) 
     $_SESSION['login'] = false; 
     //TODO: RETURN TRUE WITH AJAX 
} 
?> 

그래서 당신은 메일 mailCheck.php의 과정에서 데이터베이스에있는 경우 방법을 알고 내 기능은 기존의 수 (메일을) 알고

?

도움을 주셔서 감사합니다.

Bastien

+0

'mailCheck' - 메일 유형은 무엇입니까? 문자열, 배열, 객체? – RamRaider

답변

0

아약스는 안정적으로 값을 반환 할 수없는 본질적으로 비동기이기 때문에 - 당신이 값을 반환 할 수 있도록 할 것 Promise 이데올로기 중심으로 구축 된 fetch API를 사용할 수 있습니다 또는 당신이 아약스 콜백을 사용할 수 있습니다 메일 검사가 완료되면 서버의 응답을 기반으로 처리를 계속합니다.

fetch api를 사용하면 여러 가지 서로 다른 요청을 연결할 수 있습니다. 따라서 이전 값이 true 또는 false 인 종속성이있는 경우 ajax에서 수행 할 수있는 작업을 기다릴 수 있습니다 (콜백 및 중첩 된 아약스 요청)

function mailCheck(mail) { 
    for(i = 0; i < mail.length; i++) {/* is this an array? */ 
     if (mail[i] == "") document.getElementById("input").style.background = "#FFDDEE"; 
    } 
    var _callback=function(response){ 
     if(response===false){ 
      document.getElementById("input").style.background = "#FFDDEE"; 
     } else { 
      //TODO: GO TO NEXT STEP (PASSWORD) 
     } 
    } 

    existing.call(this, mail, _callback); 

} 

function existing(mail, callback) { 
    var xhr = new XMLHttpRequest(); 
    xhr.onreadystatechange=function(){ 
     if(this.status==200 && this.readyState==4)callback.call(this, this.response); 
    } 
    xhr.open('POST','mailcheck.php',true); 
    xhr.setRequestHeader('Content-Type','application/x-www-form-urlencoded'); 
    xhr.send('mail='+mail); 
} 

제대로 완료되면 아약스와 비교하지만, 궁극적으로 더 유연한 때 ~ 아주 복잡 fetch API를 사용하여 기본 데모.

<?php 
    if($_SERVER['REQUEST_METHOD']=='POST') { 
     ob_clean(); 

     $json=array('error'); 
     $_POST['time']=microtime(); 

     $dbhost = 'localhost'; 
     $dbuser = 'root'; 
     $dbpwd = 'xxx'; 
     $dbname = 'xxx'; 
     $db = new mysqli($dbhost, $dbuser, $dbpwd, $dbname); 


     switch($_POST['action']){ 
      case 'checkmail': 
       /* db lookup and other tests */ 
       $email=filter_var(filter_input(INPUT_POST, 'email', FILTER_SANITIZE_EMAIL), FILTER_VALIDATE_EMAIL); 
       $status=false; 

       $sql='select `username` from `users` where `email`=?'; 
       $stmt=$db->prepare($sql); 

       if($stmt){ 

        $stmt->bind_param('s', $email); 
        $result = $stmt->execute(); 

        if($result){ 
         $stmt->store_result(); 
         $stmt->bind_result($username); 
         $stmt->fetch(); 
         $stmt->close(); 
         $db->close(); 

         if($username) { 
          $_POST['username']=$username; 
          $status=true; 
         } 
        } else { 
         $status=false; 
        } 
       } else { 
        $status=false; 
       } 

       $_POST['status']=$status; 
      break; 
      case 'login': 
       /* validate user login */ 
       $email=filter_var(filter_input(INPUT_POST, 'email', FILTER_SANITIZE_EMAIL), FILTER_VALIDATE_EMAIL); 
       $password=filter_input(INPUT_POST, 'password', FILTER_SANITIZE_STRING); 
       $status=false; 

       $sql='select `username`,`token` from `users` where `email`=? and `password`=?'; 
       $stmt=$db->prepare($sql); 


       if($stmt){ 

        $stmt->bind_param('ss', $email, $password); 
        $result = $stmt->execute(); 

        if($result){ 
         $stmt->store_result(); 
         $stmt->bind_result($username, $token); 
         $stmt->fetch(); 
         $stmt->close(); 
         $db->close(); 

         if($username) { 
          $_POST['username']=$username; 
          $_POST['token']=$token; 
          $status=true; 
         } 
        } else { 
         $status=false; 
        } 
       } else { 
        $status=false; 
       } 
       $_POST['status']=$status; 
      break; 
     } 


     $json = json_encode($_POST); 

     header('Content-Type: application/json'); 
     header('HTTP/1.1 200 OK', true, 200); 
     exit($json); 
    } 
?> 
<!doctype html> 
<html> 
    <head> 
     <meta charset='utf-8' /> 
     <title>Chained Fetch</title> 

     <script> 
      var options={ 
       once:false, 
       capture:false, 
       passive:false 
      }; 

      document.addEventListener('DOMContentLoaded', function(){ 

       document.querySelector('form > input[type="button"]').onclick=function(event){ 

        var stack=[]; 
        var url=location.href; 
        var mail=document.querySelector('form > input[name="email"]'); 
        var password=document.querySelector('form > input[name="password"]'); 

        var _final=function(r){ 
         alert(r); 
        } 
        var _isvalid=function(r){ 
         if(!r.status)throw new Error(r.action+' failed'); 
         return r.status; 
        } 

        /* the urls could be totally different php scripts */ 
        stack.push({ 
         url:url, /* checkmail.php */ 
         config:{ 
          method:'POST', 
          mode:'cors', 
          credentials:'include', 
          headers:{ 'Content-Type':'application/x-www-form-urlencoded; charset=UTF-8' }, 
          body:'action=checkmail&email='+mail.value 
         } 
        }); 
        stack.push({ 
         url:url,/* login.php */ 
         config:{ 
          method:'POST', 
          mode:'cors', 
          credentials:'include', 
          headers:{ 'Content-Type':'application/x-www-form-urlencoded; charset=UTF-8' }, 
          body:'action=login&password='+password.value+'&email='+mail.value 
         } 
        }); 





        fetch(stack[0].url, stack[0].config) 
         .then(response => response.json()) 
         .then(data => _isvalid(data)) 
         .then(data => fetch(stack[1].url, stack[1].config)) 
         .then(response => response.json()) 
         .then(data => _isvalid(data)) 
         .then(_final) 
         .catch(err => alert(err.message)); 

       } 
      },options); 
     </script> 
    </head> 
    <body> 
     <form> 
      <input type='email' name='email' /> 
      <input type='password' name='password' value='knickers' /> 
      <input type='button' value='Login' /> 
     </form> 
    </body> 
</html> 
+0

답변 해 주셔서 감사합니다. 우선 메일은 문자열입니다. 그렇다면이 API에 대해서는 전혀 모른다. 따라서 귀하의 코드를 이해하려고 노력할 것입니다. mailCheck.php 파일에 "응답"(true 또는 false를 반환하는 곳)으로 뭔가를 넣어야합니까? 아니면 코드가 자동으로 이해합니까? –

+0

예, PHP에서 Ajax 콜백으로 응답을 보냅니다. – RamRaider

+0

와우 꽤 복잡하지만 결국 이해할 것입니다. 도움을 많이 주셔서 감사합니다. 지금 작업하겠습니다. –