AJAXを使用すると、確実に値を返すことができない、本質的に非同期であるため - あなたが値を返すことができるようになるか、あなたがAJAXコールバックを使用することができPromise
イデオロギーを中心に構築されfetch
APIを使用することができますメール検査が完了したときに、サーバーからの応答に基づいて処理を続行します。
fetch
apiを使用すると、さまざまなリクエストを連鎖させることができます。したがって、以前の値がtrueまたはfalseなどに依存している場合は、ajaxで行うことはできません(コールバックおよびネストされた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>
関数 'mailCheck'では' mail'の型は何ですか?文字列、配列、オブジェクト? – RamRaider