Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
183 views
in Technique[技术] by (71.8m points)

javascript - Jquery Ajax On-Focusout On-Submit - Requires 2 Clicks

Hello I have a jquery and ajax validation form, when you fill the values (wrong values) [email protected] and 1111111 in password it will give ajax validation notice (which is fine) but after that if you put in the values (correct values) [email protected] and 12345678 it requires two clicks to submit. Meaning if you put wrong values first and then put correct values then it will require two clicks to submit. following is the code. I have set the code below so you can copy and paste the code into files (filenames given before) and you will have a working model to work with. I have hardcoded the php validate file so you guys can copy and paste the code and see how it works.

index.php

<?php 
if (session_status() == PHP_SESSION_NONE) {
    session_start();
}
?>

<!DOCTYPE HTML>
<html lang="en-US">
<head>
    <meta charset="UTF-8">
</head>

<body>
    <form method="post" name="loginform" action="success.php">
        <input type="email" class="homepage"  name="user_email2" id="user_email2" placeholder="Email" maxlength="50" required />
        <div class ="errormsg" id ="errormsg6"></div>
        <input type="password" class="homepage"  name="user_password2" id="user_password2" placeholder="Password" maxlength="20" required />
        <div class ="errormsg" id ="errormsg7"></div>
        <input type="submit" name="login" id="login" value="Submit">
        <div class ="errormsglast" id ="errormsg8"></div>

    </form>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
    <script type="text/javascript" src="validatelogin.js"></script> 
</body>
</html>

validatelogin.js

$(document).ready(function()
{
    /* ----------------- Login Validations Global Variables -----------------   */
    var user_email2 = "";
    var user_emailajax2 = "";
    var user_password2 = "";
    var user_passwordajax2 = "";
    var emailformat = new RegExp(/^[+a-zA-Z0-9._-]+@[a-zA-Z0-9.-]+.[a-zA-Z]{2,4}$/i);

    /* ----------------- Define Validate Email */
    var validate_email_login = function()
    {
        var item5 = $("#user_email2").val();
        var item5 = item5.toLowerCase();
        if (item5.length < 6 || item5.length > 50)
        {
            $("#errormsg6").html("Email : 6 - 50 Characters");
            user_email2 = "";
        }
        else
        {
            $("#errormsg6").html("");
            user_email2 = item5;
            if (!emailformat.test(item5))
            {
                $("#errormsg6").html("Wrong Email Format");
                user_email2 = "";
            }
            else
            {
                $("#errormsg6").html("");
                user_email2 = item5;
                $.ajax(
                {
                    type: 'POST',
                    url: 'validatelogin.php?f=1',
                    data: "user_email2=" + item5,
                    success: function(msg)
                    {
                        if (msg == "ok")
                        {
                            user_emailajax2 = "";
                            $("#errormsg6").html("Email Does Not Exist");
                        }
                        else if (msg == "exists")
                        {
                            user_emailajax2 = item5;
                            $("#errormsg6").html("");
                        }
                    }
                });
            }
        }
    }

    /* ----------------- Define Validate Password */
    var validate_password_login = function()
    {
        var item5 = $("#user_email2").val();
        var item5 = item5.toLowerCase();
        var item6 = $("#user_password2").val();

        if (item6.length < 8 || item6.length > 20)
        {
            $("#errormsg7").html("Password : 8-20 Characters");
            user_password2 = "";
        }
        else
        {
            $("#errormsg7").html("");
            user_password2 = item6;
            if (user_email2 != "" && user_emailajax2 != "")
            {
                $.ajax(
                {
                    method: "POST",
                    url: "validatelogin.php?f=2",
                    data: "user_email2=" + item5 + "&user_password2=" + item6,
                    success: function(msg)
                    {
                        if (msg == "WrongPw")
                        {
                            user_passwordajax2 = "";
                            $("#errormsg7").html("Wrong Password");
                        }
                        else if (msg == "CorrectPw")
                        {
                            user_passwordajax2 = item6;
                            $("#errormsg7").html("");
                            /* window.location.href="manage-properties"; */
                        }
                    }
                });
            }
        }
    }

    /* ----------------- Run Functions */
    $("#user_email2").on('focusout', validate_email_login);
    $("#user_password2").on('focusout', validate_password_login);
    $("#login").on('click', validate_email_login);
    $("#login").on('click', validate_password_login);

    /* ----------------- Stop on Submit */
    $("#login").on('click', function()
    {
        if (user_email2 == "" || user_emailajax2 == "" || user_password2 == "" || user_passwordajax2 == "")
        {
            $("#errormsg8").html("Please Fill All Fields (Correctly)");
            console.log("submit false");
            return false;
        }
        else
        {
            $("#errormsg8").html("");
            console.log("submit true");
            return true;
        }
    });
});

validatelogin.php

<?php
if (session_status() == PHP_SESSION_NONE) {
    session_start();
}

if($_GET['f']==1) {
    if(isset($_POST['user_email2'])) {
        $user_email2 = strtolower($_POST['user_email2']);
        if($user_email2 == "[email protected]") {
            echo "exists";
        } else {
            echo "ok";  
        } 
    }
}

if($_GET['f']==2) { 
    if(isset($_POST['user_email2'], $_POST['user_password2'] )) {
        $user_email2 = strtolower($_POST['user_email2']);
        $user_password2 = $_POST['user_password2']; 

        if($user_email2!="[email protected]" and $user_password2!="12345678") {
            echo "WrongPw";
        } elseif($user_email2=="[email protected]" and $user_password2=="12345678") {
            echo "CorrectPw";
        }
    }
}   
?>

success.php

<?php
echo "Login Successful";
?>

Tried Solutions 1. Putting a delay on the submit button 2. On Keyup instead of on Focusout (this works but not what is required) 3. Give delay to keyup (could not get it to work with ajax - but its closer to what I require, but not exactly what I require 4. Triggering the click on submit on return true of ajax (also did not work)

I need some javascript expert to look into it and give me solution.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Okay, I don't want to be rude, but all that code is a bit of a disaster. You're calling the on click function 3 different times, you're making ajax calls to the server on every form change and on submit. Then you're actually making two separate ajax calls for the actual submit function.

The code below is a lot more compact, only ever makes one ajax call and should work. I'll explain a bit before each code block

Your form add an id so that jQuery can use serialize in the ajax call

<form method="post" id="loginform" name="loginform" action="success.php">
    <input type="email" class="homepage"  name="user_email2" id="user_email2" placeholder="Email" maxlength="50" required />
    <div class ="errormsg" id ="errormsg6"></div>
    <input type="password" class="homepage"  name="user_password2" id="user_password2" placeholder="Password" maxlength="20" required />
    <div class ="errormsg" id ="errormsg7"></div>
    <input type="submit" name="login" id="login" value="Submit">
    <div class ="errormsglast" id ="errormsg8"></div>

</form>

validatelogin.php - This should only be one call to the server, do both functions in one, return the data as json rather than echoing single values, that way you get an object back that you can parse in your jQuery code.

<?php
if (session_status() == PHP_SESSION_NONE) {
    session_start();
}

if(isset($_POST['user_email2'], $_POST['user_password2'] )) {
    $user_password2 = $_POST['user_password2']; 
    $user_email2 = strtolower($_POST['user_email2']);
    if($user_email2 != "[email protected]") {
        $data['email_check'] = 'false';
    } else {
        $data['email_check'] = 'true';
    } 
    $data = array;
    if($user_email2!="[email protected]" && $user_password2!="12345678") {
        $data['password_check'] = 'false';
    } else {
        $data['password_check'] = 'true';
    }
}
print(json_encode($data));

jQuery - I am not really sure why you're calling all these functions on blur and the multiple on clicks. Just do it in the one on click, call validate email, if that passes you move on to validate password and if that passes it makes the ajax call to actually check the details against the server.

Also avoid variable names like item5, errormsg6, to another developer that means nothing, and it won't to you in 6 months either. And don't tell people which element was wrong, ie "Incorrect password" just for security, just tell them their login details are wrong.

$(document).ready(function() {
  /* ----------------- Login Validations Global Variables -----------------   */
  var user_email2 = "";
  var user_emailajax2 = "";
  var user_password2 = "";
  var user_passwordajax2 = "";
  var emailformat = new RegExp(/^[+a-zA-Z0-9._-]+@[a-zA-Z0-9.-]+.[a-zA-Z]{2,4}$/i);
  /* ----------------- Define Validate Email */
  var validate_email_login = function() { 
    var email = $("#user_email2").val().toLowerCase();
      var errors = [];

    if (email.length < 6 || email.length > 50) {
        errors.push("Email : 6 - 50 Characters<br>");
    } 

    if (!emailformat.test(email)) {
      errors.push("Wrong Email Format");
    } 
    if( errors.length > 0 ) {
      $("#errormsg6").html(errors);
      return false;
    }
    $("#errormsg6").html();
    validate_password_login();
  }

  /* ----------------- Define Validate Password */
  var validate_password_login = function() {
    var item6 = $("#user_password2").val();

    if (item6.length < 8 || item6.length > 20) {
        $("#errormsg7").html("Password : 8-20 Characters");
        return false;
    }
    $("#errormsg7").html("");
    submitForm();
  }

  var submitForm = function() {
    $.ajax({
      type: 'POST',
      url: 'validatelogin.php',
      dataType: "json",
      data: $("#loginform").serialize(), 
      success: function(msg) {

        if(msg.email_check == 'true' && msg.password_check == 'true') {
            //do whatever it is you want to do on correct login here
        } else {
            $("#errormsg6").html("Your login details are incorrect, please check and try again");
        }
      }
    });
  }


  /* ----------------- Stop on Submit */
  $("#login").on('click', function() {
      errors = [];
    if(validate_email_login() == true) {
        alert("hi");
    }
  });
});

You can see the error validation on the jQuery end here: https://jsfiddle.net/calder12/3fhvpenr/


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...