停止提交表单(在$ .post之后尝试e.preventDefault()但它停止提交表单

时间:2015-03-25 05:26:11

标签: php jquery ajax

我在javascript中有这个

$('#submit').on('click', function(e) {  
        $('#message_line').text("");    
        if(validate_fields_on_submit()) {
            e.preventDefault();
            return;
        }   
       // e.preventDefault();
        var params = $('form').serialize(); 
        $.post('check_duplicate.php', params, function(responseText) {
            submitHandler(responseText);
        });
//      e.preventDefault();
//return false;
    });
    function submitHandler(response) {
        $('#message_line').text("");    
        response = $.trim(response);
        if(response == "" && response.indexOf("<") <= -1)
            $('#registration').submit();
        else if(response.indexOf("<") == 0) {
            var name = $('[name="regusername"]').val();
            $('#message_line').text("Some error occured, please try after some time.");  
            $("#message_line").attr("tabindex",-1).focus();
            return false;  
        } else {   
            var name = $('[name="regusername"]').val();
            var arr = response.split(',');
            arr.pop();
            arr.toString();
            $('#message_line').text("'" + name + "' already exists, Please try different username");  
            $("#regusername").focus();
            return false;
        }                                    
        $('#busy_wait').css('display','none'); 
    }

HTML CODE

<?php
    session_start();
    if ($_SERVER["REQUEST_METHOD"] == "POST") {
        include("db/helper_functions.php");
        if(validate_fields()) {
            if(!check_duplicate($_POST["regusername"])) {
                $count = insert_record($_POST["fname"],$_POST["lname"],$_POST["email"],$_POST["regusername"],$_POST["regpassword"]);
                if($count > 0) {
                    include("includes/confirmation.php");
                    exit();
                }
                else {
                    $error = "Sorry registration failed, please try again.";
                }
            }
            else {
                $error = "Username already exists, please try different username.";
            }
        }
    }
    $page_title = "Registration";
    if(isset($_SESSION["username"]))
        include('includes/header_authorized.html');
    else
        include('includes/header.html');

?>

<div class="container">
    <div class="regform">
        <form  name="registration" id="registration" method="post" action="registration.php">
            <p><span class="req">* required field.</span></p>                      
            <ul>
                <li><label for="fname">First Name:</label>
                    <input type="text" class="textboxborder" id="fname" name="fname" size="20" maxlength="25" autofocus="autofocus" value="<?php if(isset($_POST['fname'])) echo $_POST['fname'];?>"/>
                    <span class="error" id="errfname">*<?php if(isset($errfname)) echo $errfname;?></span>
                </li>
                <li><label for="lname">Last Name:</label>
                    <input type="text" class="textboxborder" id="lname" name="lname" size="20" maxlength="25" value="<?php if(isset($_POST['lname'])) echo $_POST['lname'];?>"/>
                    <span class="error" id ="errlname">*<?php if(isset($errlname)) echo $errlname;?></span>
                </li> 
                <li><label for="email">Email:</label>
                    <input type="text" class="textboxborder" name="email" id="email" size="40" maxlength="50" placeholder="abc@xyz.com" value="<?php if(isset($_POST['email'])) echo $_POST['email'];?>"/> 
                    <span class="error" id="erremail">*<?php if(isset($erremail)) echo $erremail;?></span>  
                </li>
                <li><label for="regusername">Username:</label>
                    <input type="text" name="regusername" id="regusername" size="20" maxlength="30" value="<?php if(isset($_POST['regusername'])) echo $_POST['regusername'];?>"/> 
                    <span class="error" id="errregusername">*<?php if(isset($errregusername)) echo $errregusername;?></span> 
                </li>
                <li><label for="regpassword">Password:</label>
                    <input type="password" name="regpassword" id="regpassword" size="20" maxlength="15" value="<?php if(isset($_POST['regpassword'])) echo $_POST['regpassword'];?>"/> 
                    <span class="error" id="errregpassword">*<?php if(isset($errregpassword)) echo $errregpassword;?></span> 
                </li>
                <li><label for="regconpassword">Confirm Password:</label>
                    <input type="password" name="regconpassword" id="regconpassword" size="20" maxlength="15"/> 
                    <span class="error" id="errregconpassword">*<?php if(isset($errregconpassword)) echo $errregconpassword;?></span> 
                </li>
            </ul>
            <div id="message_line">&nbsp;<?php if(isset($error)) echo $error;?></div>
            <div class="buttons">
                <input type="reset" value="Reset" id="reset"/>
                <input type="submit" value="Submit" />
            </div> 
        </form>  
        <img src="images/loading.gif" id="busy_wait" alt="busy wait icon" />  
    </div> 
</div>
</body>
</html>

如果在提交处理程序控制中进入,否则阻止表单提交没有停止,我尝试return false;我尝试在ajax调用之前和之后的不同位置使用e.preventDefault();但是停止表单提交即使在验证成功并从check_duplicate.php成功返回之后 任何帮助将不胜感激。

2 个答案:

答案 0 :(得分:1)

要防止表单提交,最好的方法是在onclick客户端事件上返回false 例如

$('#submit').click(function(){

 return false;

})

答案 1 :(得分:1)

假设你有一个id = submit的提交按钮,我会

  1. 重命名按钮,因为调用任何提交都是不好的做法,因为您需要以编程方式实际提交表单。

  2. 将处理程序移动到表单提交事件 - 我个人从不将处理程序附加到提交按钮

  3. 如果验证返回false,我假设您不想提交

  4. 喜欢这个

    $('#registration').on('submit', function(e) {  
        e.preventDefault();
        $('#message_line').text("");    
        if(!validate_fields_on_submit()) { // I assume you meant NOT
          return;
        }   
        var params = $(this).serialize(); 
        $.post('check_duplicate.php', params, function(responseText) {
            submitHandler(responseText);
        });
    });
    

    这篇文章可以写成

    $.post('check_duplicate.php', params, submitHandler);
    

    更新以下是完整的脚本 - 注意重命名以重命名任何名称=提交或id =提交给其他人

    $(function() {
      $('#registration').on('submit', function(e) {  
        e.preventDefault();
        $('#message_line').text("");    
        if(!validate_fields_on_submit()) { // I assume you meant NOT
          return;
        }   
        $('#busy_wait').show(); 
        $.post('check_duplicate.php', $(this).serialize(), function(response) {
          response = $.trim(response);
         if (response == "" && response.indexOf("<") <= -1) {
            $('#registration').submit(); // actually submit the form
          }
          else if(response.indexOf("<") == 0) {
            var name = $('[name="regusername"]').val();
            $('#message_line').text("Some error occured, please try after some time.");  
            $("#message_line").attr("tabindex",-1).focus();
          } else {   
            var name = $('[name="regusername"]').val();
            $('#message_line').text("'" + name + "' already exists, Please try different username");  
            $("#regusername").focus();
          }                                    
          $('#busy_wait').hide();
      });
    }); 
    

    UPDATE3:

    $(function() {
      $('#registration').on('submit', function(e) {  
        e.preventDefault();
        $('#message_line').text("");    
        if(!validate_fields_on_submit()) { // I assume you meant NOT
          return;
        }   
        $('#busy_wait').show(); 
        var $thisForm=$(this); // save for later
        var params = $thisForm.serialize(); 
        $.post('check_duplicate.php', params, function(response) {
          response = $.trim(response);
         if (response == "" && response.indexOf("<") <= -1) {
            // actually submit the form
            $.post($thisForm.prop("action"), params, function(response) {
              if (response.indexOf("success") !=-1) {    
                $('#message_line').text(response);
              }
              else {
                $('#message_line').text("something went wrong");
              }
              $('#busy_wait').hide();
            });
         }
         else if(response.indexOf("<") == 0) {
            var name = $('[name="regusername"]').val();
            $('#message_line').text("Some error occured, please try after some time.");  
            $("#message_line").attr("tabindex",-1).focus();
          } else {   
            var name = $('[name="regusername"]').val();
            $('#message_line').text("'" + name + "' already exists, Please try different username");  
            $("#regusername").focus();
          }                                    
          $('#busy_wait').hide();
      });
    });