OnSubmit Вызывает функцию, которая вызывает функцию 3 и проверяет return_type, но функция 1 не вызывается - PullRequest
0 голосов
/ 08 января 2020
  1. Форма, которая принимает значения от пользователя, OnSubmit вызывает функцию check_three_fun c ()
image check_three_fun c () вызывает 3 функции, упомянутые ниже в коде, и возвращает return_type, так что если false, то он не сможет отправить форму
function check_three_func(){
    var check_email_func=check_email();
    var click_to_func=click_to();
    var check_func=check();
    if( check_email_func==true && click_to_func==true && check_func==true){
      return true;
      console.log("all true");
    }
    else{
      return false;
      console.log(" false");
    }
}

3.check_email () is не получается вызвать OnSubmit

function check_email(){
  var email = document.getElementById("uemail").value;
  if (window.XMLHttpRequest) {// code for IE7+, Firefox, Chrome, Opera, Safari
    xhttp=new XMLHttpRequest();
}
 else {// code for IE6, IE5
    xhttp=new ActiveXObject("Microsoft.XMLHTTP");
  }

  xhttp.onreadystatechange=function(){
    if (xhttp.readyState == 4 && xhttp.status == 200) {
      document.getElementById("alert").style.display="inline";
      if(xhttp.responseText=="EMP"){
        document.getElementById("alert").innerHTML="<br><span class='badge badge-pill badge-info'>fill out emai id</span>";
        console.log("Email id empty return false");
        return false;
      }
      else if(xhttp.responseText=="OK"){
      document.getElementById("alert").innerHTML="<br><span class='badge badge-pill badge-success' >welcome new user</span>";
      //document.getElementById("submit-button").disabled = false;
      console.log("New email id return true");
      return true;
      }
      else if(xhttp.responseText=="NO"){
      document.getElementById("alert").innerHTML="<br><span class='badge badge-pill badge-danger'>Email Already Exist</span>";
      //document.getElementById("submit-button").disabled = true;
      console.log("Email id already exsist return false");
      return false;
      }
      else{
        document.getElementById("alert").innerHTML=xhttp.responseText;
        //document.getElementById("submit-button").disabled = true;
        console.log("Error fetching email id");
        return false;
      }
    }
  };
  xhttp.open("GET","emailvalidate.php?uemail="+email,true);
  xhttp.send();
}
В то время как функция click_to () и check () вызываются и дают желаемую проверку
function click_to(){
  var code = document.getElementById("captcha").value;
  if (window.XMLHttpRequest) {// code for IE7+, Firefox, Chrome, Opera, Safari
    xhttp=new XMLHttpRequest();
}
 else {// code for IE6, IE5
    xhttp=new ActiveXObject("Microsoft.XMLHTTP");
  }

  xhttp.onreadystatechange=function(){
  if (xhttp.readyState == 4 && xhttp.status == 200) {
    document.getElementById("captcha-result").style.display="inline";
    if(xhttp.responseText=="EMP"){
      document.getElementById("captcha-result").innerHTML="<br><span class='badge badge-pill badge-info'>Cannot be Kept Empty</span>";
      //document.getElementById("submit-button").disabled = true;
      console.log("Cannot be empty return false");
      return false;
    }
    else if(xhttp.responseText=="INVALID"){
      document.getElementById("captcha-result").innerHTML="<br><span class='badge badge-pill badge-info'>Invalid Captcha code</span>";
      //document.getElementById("submit-button").disabled = true;
      console.log("Invalid code return false");
      return false;
    }
    else if(xhttp.responseText=="VALID"){
    document.getElementById("captcha-result").innerHTML="<br><span class='badge badge-pill badge-success' >Valid Captcha code</span>";
    //document.getElementById("submit-button").disabled = false;
    console.log("valid code return true");
    return true;
    }
    else{
      document.getElementById("captcha-result").innerHTML=xhttp.responseText;
    //  document.getElementById("submit-button").disabled = true;
    console.log("Error return false");
      return false;
    }
  }
};
xhttp.open("GET","submited_captcha.php?captcha="+code,true);
xhttp.send();
}
Код функции проверки () ниже
function check(){
    var uname=document.forms["register_form"]["uname"].value;
    var uemail=document.forms["register_form"]["uemail"].value;
    var upassword=document.forms["register_form"]["upassword"].value;
    var ucpassword=document.forms["register_form"]["ucpassword"].value;
    var captcha=document.forms["register_form"]["captcha"].value;
    var upassword_length=upassword.length;
    if(uname=="" || uemail=="" || upassword=="" || ucpassword=="" || captcha==""){
      alert("all fields must be filled out");
      console.log("all fields must be filled");
      return false;
    }
    else if (upassword.length <= 6 ) {
      alert("Password length should be more than 6 Characters ");
      console.log("pass length not more than 6");
      return false;
    }
    else if(upassword != ucpassword){
      alert("Confirm password should be same as password");
      console.log("pass not matching");
      return false;
    }
    else{
      alert("All fields filled");
      console.log("true all fields filled");
      return true;
    }

  }

6.check_email () и click_to () содержат ajax скриптов. Ниже приведена страница php, которую ajax скрипт в chech_email () вызывает

<?php
$eid=$_GET['uemail'];
if(empty($eid)){
  echo "EMP";
}
else{
$conn=mysqli_connect("localhost","root","","db_pagination");
if(!$conn){
  die("connection error".mysqli_connect_error());
}
$sql="select email_id from user where email_id='$eid' ";
$result=mysqli_query($conn,$sql);
if(!$result){
  echo "error:".mysqli_error($conn);
}
$row=mysqli_num_rows($result);
if($row==0){
  echo "OK";  
}
if($row > 0){
  echo "NO";
}

}
 ?>

Ответы [ 2 ]

0 голосов
/ 08 января 2020

обновить значение параметра asyn c на false. Если значение параметра asyn c равно false, метод send () не возвращается до тех пор, пока не будет получен ответ.

xhttp.open("GET","emailvalidate.php?uemail="+email,false);

Попробуйте следующий код:

function check_email(){
  var email = document.getElementById("uemail").value;
  if (window.XMLHttpRequest) {// code for IE7+, Firefox, Chrome, Opera, Safari
    xhttp=new XMLHttpRequest();
}
 else {// code for IE6, IE5
    xhttp=new ActiveXObject("Microsoft.XMLHTTP");
  }
  result = true; // create a variable result and by default make it true.
  xhttp.onreadystatechange=function(){
    if (xhttp.readyState == 4 && xhttp.status == 200) {
      document.getElementById("alert").style.display="inline";
      if(xhttp.responseText=="EMP"){
        document.getElementById("alert").innerHTML="<br><span class='badge badge-pill badge-info'>fill out emai id</span>";
        console.log("Email id empty return false");
        result = false;
      }
      else if(xhttp.responseText=="OK"){
      document.getElementById("alert").innerHTML="<br><span class='badge badge-pill badge-success' >welcome new user</span>";
      //document.getElementById("submit-button").disabled = false;
      console.log("New email id return true");
      }
      else if(xhttp.responseText=="NO"){
      document.getElementById("alert").innerHTML="<br><span class='badge badge-pill badge-danger'>Email Already Exist</span>";
      //document.getElementById("submit-button").disabled = true;
      console.log("Email id already exsist return false");
      result = false;
      }
      else{
        document.getElementById("alert").innerHTML=xhttp.responseText;
        //document.getElementById("submit-button").disabled = true;
        console.log("Error fetching email id");
        result = false;
      }
    }
  };
  xhttp.open("GET","emailvalidate.php?uemail="+email,false);
  xhttp.send();

  return result;  //at last return the result.
}
0 голосов
/ 08 января 2020

check_email является асинхронной c функцией. Вот почему вы не получаете обратный результат. Вы должны вызвать функцию, как показано ниже.

Добавьте асин c перед ключевым словом function и добавьте ключевое слово await перед check_email function.

async function check_three_func() {
    var check_email_func = await check_email();
    var click_to_func = click_to();
    var check_func = check();
    if (check_email_func && click_to_func && check_func) {
        return true;
        console.log("all true");
    }
    else {
        return false;
        console.log(" false");
    }
}
Сверните ваш код ajax в обещании и разрешите или отклоните на основе ответа, а затем верните это обещание.
function check_email() {

    return new Promise((resolve, reject) => {
        var email = document.getElementById("uemail").value;
        if (window.XMLHttpRequest) {// code for IE7+, Firefox, Chrome, Opera, Safari
            xhttp = new XMLHttpRequest();
        }
        else {// code for IE6, IE5
            xhttp = new ActiveXObject("Microsoft.XMLHTTP");
        }
        xhttp.onreadystatechange = function () {
            if (xhttp.readyState == 4 && xhttp.status == 200) {
                document.getElementById("alert").style.display = "inline";
                if (xhttp.responseText == "EMP") {
                    document.getElementById("alert").innerHTML = "<br><span class='badge badge-pill badge-info'>fill out emai id</span>";
                    console.log("Email id empty return false");
                    reject(false);
                }
                else if (xhttp.responseText == "OK") {
                    document.getElementById("alert").innerHTML = "<br><span class='badge badge-pill badge-success' >welcome new user</span>";
                    //document.getElementById("submit-button").disabled = false;
                    console.log("New email id return true");
                    resolve(true);
                }
                else if (xhttp.responseText == "NO") {
                    document.getElementById("alert").innerHTML = "<br><span class='badge badge-pill badge-danger'>Email Already Exist</span>";
                    //document.getElementById("submit-button").disabled = true;
                    console.log("Email id already exsist return false");
                    reject(false);
                }
                else {
                    document.getElementById("alert").innerHTML = xhttp.responseText;
                    //document.getElementById("submit-button").disabled = true;
                    console.log("Error fetching email id");
                    reject(false);
                }
            }
        };
        xhttp.open("GET", "emailvalidate.php?uemail=" + email, true);
        xhttp.send();
    });

}

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...