简体   繁体   中英

Storing Ajax success data into javascript variable to use in other js function

I am currently doing login form and I have database with the username and password. I've already done comparing if username and password is match with that username But I want to display username is not exist when I click the submit button using the variable come from ajax response. I've already done it but the variable is stored inside html tag.

Here is my old code

function checkUsn(){
    var usn = document.getElementById("usn").value;
    if(usn){
        $.ajax({
            type: 'post',
            url: 'checkdata.php',
            data: {
                emp_username: usn,
            },
            success: function(response){
                $('#status').html(receiveUsn);
                if (response == "OK"){
                    return true;
                }else{
                    return false;
                }
            }
        });
    }else{
        $('#status').html("");
        return false;
    }
}

I want something like this but this code below didn't work

function checkUsn(receiveUsn){
    var usn = document.getElementById("usn").value;
    if(usn){
        $.ajax({
            type: 'post',
            url: 'checkdata.php',
            data: {
                emp_username: usn,
            },
            success: function(response){
                var receiveUsn = response; //I want to use this for other function
                $('#status').html(receiveUsn);
                if (response == "OK"){
                    return true;
                }else{
                    return false;
                }
            }
        });
    }else{
        $('#status').html("");
        return false;
    }
}

Then I will use the variable come from ajax on this function

function checkall(receivePw, receiveUsn)
{
    if(receiveUsn == "OK" && receivePw == "MATCH"){
        return true;
    }else{
        return false;
    }
}

php code

<?php
include 'db_config.php';
$conn = new mysqli($db_servername, $db_username, $db_password, $db_name);

if(isset($_POST['emp_username'])){
    $usn = $_POST['emp_username'];

    $checkdata = "SELECT emp_username FROM emp_details where emp_username='$usn'";

    $query = mysqli_query($conn, $checkdata);

    if(mysqli_num_rows($query) > 0){
        echo "OK";
    }else{
        echo "Your Username not exist";
    }
    exit();
}

if(isset($_POST['emp_pw']) && isset($_POST['emp_usn'])){
    $pw = $_POST['emp_pw'];
    $usn = $_POST['emp_usn'];

    $get_pw = "SELECT emp_password FROM emp_details where emp_username='$usn'";

    $query = mysqli_query($conn, $get_pw);

    //$get_num_rows = mysqli_num_rows($query);
    //echo $get_num_rows;

    $row = mysqli_fetch_assoc($query);
    //echo $row["emp_password"];

    // check if password is match with username
    if($pw == $row["emp_password"]){
        echo "MATCH";
    }else{
        echo "Wrong password";
    }
    exit();
}
?>

login form

<form class="modal-content animate" action="/login_action.php" method="post" onsubmit="return checkall();">
    <div class="container">
      <span onclick="document.getElementById('id01').style.display='none'" class="close" title="Close Modal">&times;</span>
      <div class="col-lg-3 col-md-3 col-sm-3 col-xs-3"></div>
      <img class="avatar img-responsive col-lg-6 col-md-6 col-sm-6 col-xs-6" src="img/employee_avatar.png" alt="Avatar">
      <div class="col-lg-3 col-md-3 col-sm-3 col-xs-3"></div>
    </div>
    <div class="container">
      <label for="usn"><b>Username</b></label>
      <input id="usn" type="text" placeholder="Enter Username" name="usn" onkeyup="getPw();checkUsn();" required>

      <label for="pw"><b>Password</b></label>
      <input id="pw" type="password" placeholder="Enter Password" name="pw" onkeyup="getPw();checkUsn();" required>

      <button type="submit">Login</button>
      <label>
        <input type="checkbox" checked="checked" name="remember"> Remember me
      </label>
    </div>

    <div class="container" style="background-color:#f1f1f1">
      <button type="button" onclick="document.getElementById('id01').style.display='none'" class="cancelbtn">Cancel</button>
      <span class="psw">Forgot <a href="#">password?</a></span>
    </div>
    <span id="status">status</span><br>
    <span id="status2">status</span><br>
    <span id="status3">status</span>
  </form>

Please help Thank you!!!

您需要在Java脚本开始时声明变量'receiveUsn',这样它将成为全局变量。问题是您已经在ajax成功函数中声明了var receiveUsn,因此它现在是局部变量,不能在其他变量中使用函数.global可以解决您的问题

In a <script> tag you need to declare a variable at the root level, this will create the global variable. It's considered best practice not to pollute the global space so declare an object at the global level and use that to store your global variables.

<script>
  var myGlobalContainer = {};
</script>

Now in the JavaScript code on the page you can use the myGlobalContainer object.

 // set a value
 myGlobalContainer.hello = "world";

 // read a value
 console.log(myGlobalContainer.hello);
 // "world"

Initialise a variable on top of Javascript:

myglobalvariable = '';

Now store your ajax input in variable and it's accessible everywhere:

......
success: function(response){
    myglobalvariable = response;
    $('#status').html(receiveUsn);
......

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM