duanqiang9212 2016-08-11 12:32
浏览 58
已采纳

无法获取event.preventDefault()或返回false工作。 一直在尝试从早到晚

I have been creating a form that for users to log into my site that uses jquery to preform login validation and also has a PHP fallback just in case Javascript is disabled. The user's login form in itself is a lightbox. The way I am trying to design it is so that if there's an error, the error message will appear directly in the lightbox without closing it or redirecting the user. I am basically checking to things. If the 'username' and 'password' field have been filled and if the 'username' and 'password' fields can be validated. Javascript works perfectly when I check to see if the fields have been filled out. The 'return false' works, the error message appears inside the lightbox and everything is 'honky dory'. but when it comes to validation, I use ajax to check the database and if there's a problem it does not return false.

Actually what's happening is that the error message 'will' appear at the top of the lightbox for a split second and then it submits to PHP and PHP is redirecting it.

So here is the breakdown of the code.

$('body').on('click','[name=submit11]',function(){
     $('.error').remove();
     var req = ['username','password'];
     var div = '#login_form';
     validate(div,req);
     if($('.error').length == 0){
        var login = true;
        var username = $(this).siblings('[name=username]').val();
        var password = $(this).siblings('[name=password]').val();
        $.post('../ajax/multipurpose.php',    {login:login,username:username,password:password},function(data){
            if($.trim(data) != ''){
                $('#login_form').prepend("<div class='error'>"+data+"</div>");
            }                                                                             
        });
    }
    if($('.error').length > 0){
        event.stopPropagation();
        return false;
    }
});

The validate function is a custom function I am using in jquery and that's working perfectly. The problem begins inside the second if statement after the ajax has been performed. In this if statement, there will be an error if ajax finds an error. Here is the code that's inside the multipurpose.php page.

//Used to validate the username and password via ajax
if(isset($_POST["login"])):
    $username = trim($_POST["username"]);
    $password = trim($_POST["password"]);
    if(!$found_user = User::authenticate($username,$password)):
        echo "Username/Password combination is invalid.";
    endif;
endif;

Another problem that I noticed is that if there is an error and I type alert($('.error').length) the value of 0 will show in the alert box and then after I click on "OK" in the alert box the value will appear in the lightbox and then submit to PHP. This is only for the ajax portion, not for the validate() custom function. Here is the code for the validate() function just in case anyone needs to see it.

function validate(div,fields){
    var boxes = ['pounds_or_kilos','activity'];
    $(div+' .error').remove();
    $(fields).each(function(key,value){
        if($.inArray(value,boxes) == -1){
            text = $('[name='+value+']').val();
            if($.trim(text) == ''){
                removeLoader();
                addError(div,value);
            }
        }else if(!$('[name='+value+']:checked').length){
            addError(div,value);
        }
    });
}

I've tried EVERYTHING inside that second if statement to stop it from submitting. I've tried return false...in which I use in MANY areas of the site without problems, I tried event.preventDefault(), I've tried putting an e inside the click function and using e.preventDefault(), I've also tried the event.stopPropagation() and still nothing. Someone please help me.

  • 写回答

1条回答 默认 最新

  • duanlan6259 2016-08-11 12:41
    关注

    $.post is async. So if there is error, you append it after the second check if($('.error').length > 0) and so you didn't prevent form submit behaviour.

    What you can do is prevent this behaviour in all cases and if no error regarding ajax request, then submit form manually (using native DOM method), e.g:

    $('body').on('click', '[name=submit11]', function() {
      var form = $(this).closest('form').get(0);
      $('.error').remove();
      var req = ['username', 'password'];
      var div = '#login_form';
      validate(div, req);
      if ($('.error').length == 0) {
        var login = true;
        var username = $(this).siblings('[name=username]').val();
        var password = $(this).siblings('[name=password]').val();
        $.post('../ajax/multipurpose.php', {
          login: login,
          username: username,
          password: password
        }, function(data) {
          if ($.trim(data) != '') {
            $('#login_form').prepend("<div class='error'>" + data + "</div>");
          }
          else {
             form.submit();
          }
        });
      }
      return false;
    });
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 luckysheet
  • ¥15 ZABBIX6.0L连接数据库报错,如何解决?(操作系统-centos)
  • ¥15 找一位技术过硬的游戏pj程序员
  • ¥15 matlab生成电测深三层曲线模型代码
  • ¥50 随机森林与房贷信用风险模型
  • ¥50 buildozer打包kivy app失败
  • ¥30 在vs2022里运行python代码
  • ¥15 不同尺寸货物如何寻找合适的包装箱型谱
  • ¥15 求解 yolo算法问题
  • ¥15 虚拟机打包apk出现错误