JQuery的Ajax On-Focusout On-Submit - 需要2次点击 [英] Jquery Ajax On-Focusout On-Submit - Requires 2 Clicks

查看:90
本文介绍了JQuery的Ajax On-Focusout On-Submit - 需要2次点击的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

你好我有一个jQuery和ajax验证表单,当你填充密码的值(错误值)x @ x.com和1111111时,它会给ajax验证通知(这很好),但是之后如果你把值(正确值)example@example.com和12345678需要两次点击才能提交​​。这意味着如果您先输入错误的值然后输入正确的值,则需要点击两次才能提交。以下是代码。我已经在下面设置了代码,以便您可以将代码复制并粘贴到文件中(之前给出的文件名),并且您将有一个可用的工作模型。我对PHP验证文件进行了硬编码,以便您可以复制和粘贴代码并查看它的工作原理。 $ b

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

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

< body>
< form method =postname =loginformaction =success.php>
< input type =emailclass =homepagename =user_email2id =user_email2placeholder =Emailmaxlength =50required />
< div class =errormsgid =errormsg6>< / div>
< div class =errormsgid =errormsg7>< / div>
< input type =submitname =loginid =loginvalue =Submit>
< div class =errormsglastid =errormsg8>< / div>

< / form>
< script src =https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js>< / script>
< script type =text / javascriptsrc =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);

/ * -----------------定义验证电子邮件地址* /
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,
成功:函数(msg)
{
if(msg ==ok)
{
user_emailajax2 =;
$( #errormsg6)。html(Email Does Not Exist);
}
else if(msg ==exists)
{
user_emailajax2 = item5;
$(#errormsg6)。html();
}
}
});
}
}
}

/ * -----------------定义验证密码* /
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字符);
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; * /
}
}
});
}
}
}

/ * -----------------运行函数* /
$(#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);
$ b $ * -----------------停止提交* /
$(#login)。on('click',函数()
{
if(user_email2 ==|| user_emailajax2 ==|| user_password2 ==|| user_passwordajax2 ==)
{
$(#errormsg8)。html(请填写所有字段(正确));
console.log(submit false);
return false;
}
else
{
$(#errormsg8)。html();
console.log(submit true);
return true;
}
});
}); b


$ b

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 ==example@example.com){
echoexists;
} else {
echook;



$ b if($ _ GET ['f'] == 2){
if(isset($ _ POST ['user_email2 '],$ _POST ['user_password2'])){
$ user_email2 = strtolower($ _ POST ['user_email2']);
$ user_password2 = $ _POST ['user_password2'];
$ b $ if if($ user_email2!=example@example.comand $ user_password2!=12345678){
echoWrongPw;
} elseif($ user_email2 ==example@example.com和$ user_password2 ==12345678){
echoCorrectPw;
}
}
}
?>

success.php

 <?php 
echo登录成功;
?>

尝试的解决方案
1.延迟提交按钮
2.在Keyup上,而不是在Focusout上(这个方法可行,但不是必需的)
3.延迟keyup(不能让它与ajax一起工作 - 但它更接近我的要求,但不完全是我所要求的
4.触发点击提交返回true的ajax(也没有工作)

我需要一些JavaScript专家来看看进入它,并给我的解决方案。

解决方案

好的,我不想粗鲁,但所有的代码是有点你在3次不同的次数上调用了点击函数,你在每一次表单变更和提交时都会对服务器进行ajax调用,然后你实际上为实际提交函数做了两次单独的ajax调用。 / p>

下面的代码更加紧凑,只有一次调用ajax并且应该可以工作,在每个代码块之前我会稍微解释一下



您的表单添加一个id,以便jQuery可以在ajax调用中使用序列化

 < form method =postid =loginformname =loginformaction =success.php> 
< input type =emailclass =homepagename =user_email2id =user_email2placeholder =Emailmaxlength =50required />
< div class =errormsgid =errormsg6>< / div>
< div class =errormsgid =errormsg7>< / div>
< input type =submitname =loginid =loginvalue =Submit>
< div class =errormsglastid =errormsg8>< / div>

< / form>

validatelogin.php - 这应该只是一次调用服务器,在一个函数中执行这两个函数,将数据作为json返回,而不是回显单个值,这样您就可以返回一个可以在jQuery代码中解析的对象。 > <?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!=example@example.com){
$ data ['email_check'] ='false';
} else {
$ data ['email_check'] ='true';
}
$ data = array;
if($ user_email2!=example@example.com&& $ user_password2!=12345678){
$ data ['password_check'] ='false';
} else {
$ data ['password_check'] ='true';
}
}
print(json_encode($ data));

jQuery - 我不确定为什么要调用所有这些功能模糊和多次点击。只需点击一下,然后调用验证电子邮件,如果通过,您就可以继续验证密码,如果通过,则会使ajax调用实际检查服务器上的详细信息。



还要避免像其他开发者那样的变量名称,如item5,errormsg6,这意味着什么也没有,并且在6个月内也不会给您。并且不要告诉人们哪些元素是错误的,即为了安全起见不正确的密码,只是告诉他们他们的登录详细信息是错误的。

  $(document).ready(function(){
/ * -----------------登录验证全局变量--------- -------- * /
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);
/ * -----------------定义验证电子邮件地址* /
var validate_email_login = function(){
var email = $(#user_email2)。val()。toLowerCase();
var errors = [];

if(email.length< 6 || email (电子邮件:6 - 50字符< br>);
}

if(!emailformat.test(email) ){
errors.push(错误的电子邮件格式);
}
if(errors.length> 0){
$(#err ormsg6\" )HTML(错误)。
返回false;
}
$(#errormsg6)。html();
validate_password_login();
}

/ * -----------------定义验证密码* /
var validate_password_login = function(){
var item6 = $(#user_password2)。val(); (item6.length< 8 || item6.length> 20){
$(#errormsg7)。html(Password:8-20 Characters);


返回false;
}
$(#errormsg7)。html();
submitForm();
}

var submitForm = function(){
$ .ajax({
type:'POST',
url:'validatelogin.php' ,
dataType:json,
data:$(#loginform)。serialize(),
成功:函数(msg){

if msg.email_check =='true'&& msg.password_check =='true'){
//在正确的登录处执行任何操作
} else {
$(#errormsg6)。html(您的登录信息不正确,请检查并再试一次);
}
}
});
}


/ * -----------------停止提交* /
$(#login ).on('click',function(){
errors = [];
if(validate_email_login()== true){$ b $ alert(hi);
}
});
});

您可以在这里看到jQuery结尾处的错误验证: https://jsfiddle.net/calder12/3fhvpenr/


Hello I have a jquery and ajax validation form, when you fill the values (wrong values) x@x.com and 1111111 in password it will give ajax validation notice (which is fine) but after that if you put in the values (correct values) example@example.com 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 == "example@example.com") {
            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!="example@example.com" and $user_password2!="12345678") {
            echo "WrongPw";
        } elseif($user_email2=="example@example.com" 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.

解决方案

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 != "example@example.com") {
        $data['email_check'] = 'false';
    } else {
        $data['email_check'] = 'true';
    } 
    $data = array;
    if($user_email2!="example@example.com" && $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/

这篇关于JQuery的Ajax On-Focusout On-Submit - 需要2次点击的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆