【问题标题】:Jquery form only working the first time you submit it, and not the secondJquery 表单仅在您第一次提交时工作,而不是第二次
【发布时间】:2011-05-25 07:25:47
【问题描述】:

我有一个表单,您可以将数据添加到数据库中。这一切都是用 jquery 和 ajax 完成的,所以当你按下提交时,它会验证代码,然后如果一切正确,它会提交发布数据而不刷新页面。问题是表单第一次工作,但是当你用表单提交另一个条目时它不起作用。我认为这与它有关

$(document).ready(function(){

但我真的不知道。我在下面粘贴了一些代码。它很长,但这应该提供足够的信息来了解它在做什么。 整个js文件在http://www.myfirealert.com/callresponse/js/AddUser.js

$(document).ready(function(){
$('#AddCaller').click(function(e){

    //stop the form from being submitted
    e.preventDefault();

    /* declare the variables, var error is the variable that we use on the end
    to determine if there was an error or not */
    var error = false;
    var Firstname = $('#Firstname').val();
    ...OTHER FORM FIELDS HERE

    /* in the next section we do the checking by using VARIABLE.length
    where VARIABLE is the variable we are checking (like name, email),
    length is a javascript function to get the number of characters.
    And as you can see if the num of characters is 0 we set the error
    variable to true and show the name_error div with the fadeIn effect. 
    if it's not 0 then we fadeOut the div( that's if the div is shown and
    the error is fixed it fadesOut. */


    if(Firstname.length == 0){
        var error = true;
        $('#Firstname_error').fadeIn(500);
    }else{
        $('#Firstname_error').fadeOut(500);
    }
    if(Lastname.length == 0){
        var error = true;
        $('#Lastname_error').fadeIn(500);
    }else{
        $('#Lastname_error').fadeOut(500);
    }
    ...MORE CONDITIONAL STATEMENTS HERE




    //now when the validation is done we check if the error variable is false (no errors)
    if(error == false){
        //disable the submit button to avoid spamming
        //and change the button text to Sending...
        $('#AddCaller').attr({'disabled' : 'true', 'value' : 'Adding...' });

        /* using the jquery's post(ajax) function and a lifesaver
        function serialize() which gets all the data from the form
        we submit it to send_email.php */
        $.post("doadd.php", $("#AddCaller_form").serialize(),function(result){
            //and after the ajax request ends we check the text returned
            if(result == 'added'){

                 //$('#cf_submit_p').remove();
                //and show the success div with fadeIn
                $('#Add_success').fadeIn(500);
                 $('#AddCaller').removeAttr('disabled').attr('value', 'Add A Caller');
                 document.getElementById('Firstname').value = "";
                 document.getElementById('Lastname').value = "";
                 document.getElementById('PhoneNumber').value = "";
                 document.getElementById('DefaultETA').value = "";
                 document.getElementById('Apparatus').value = "";
                 document.getElementById('DefaultLocation').value = "";


                 setTimeout(" $('#Add_success').fadeOut(500);",5000);

            }else if(result == 'alreadythere'){
                                    //checks database to see if the user is already there
                $('#Alreadythere').fadeIn(500);
                $('#AddCaller').removeAttr('disabled').attr('value', 'Add A Caller');
            }
            else{
                //show the failed div
                $('#Add_fail').fadeIn(500);
                //reenable the submit button by removing attribute disabled and change the text back to Send The Message
                $('#AddCaller').removeAttr('disabled').attr('value', 'Send The Message');

            }
        });
    }
});    
});

现在,您第一次使用该表单时效果很好。并且该按钮被重新启用,但是当您尝试进行另一个条目并单击该按钮时,没有任何反应。

感谢您的帮助!

编辑:第一次提交表单后,按钮仍处于启用状态,您可以单击它,但是当您单击它时,没有任何反应...即使您不填写表格。就像表单的点击事件不是第一次触发一样。

EDIT2 根据要求,我将发布 HTML,它位于受密码保护的站点后面,因此我无法向您发送页面链接。

<form action='addcallers.php' method='post' id='AddCaller_form'>

 <h2>Add Callers</h2>
 <p>
 First Name:
 <div id='Firstname_error' class='error'> Please Enter a First Name</div>
 <div><input type='text' name='Firstname' id='Firstname'></div>
 </p>

 <p>
 Last Name:
 <div id='Lastname_error' class='error'> Please Enter a Last Name</div>
 <div><input type='text' name='Lastname' id='Lastname'></div>
 </p>
 ...MORE FORM FIELDS HERE


 <div style="display:none;">
 <input type='text' name='DefaultLocation' id='DefaultLocation' value= "Sometthing"      readonly=readonly >

 </div>
 </p>

 <p>




 <div id='Add_success' class='success'> The user has been added</div>
 <div id='Alreadythere' class='error'> That user is already in the database</div>
 <div id='Add_fail' class='error'> Sorry, don't know what happened. Try later.</div>
 <p id='cf_submit_p'>
 <input type='submit' id='AddCaller' value='Send The Message'>
 </p>
 </form>  

 </div>

EDIT3 页面上还有其他 ajax,但它是直接用 javascript 编写的。我不确定这是否会以任何方式影响功能。但如果需要,我也可以发布该 ajax。

EDIT4我从http://web.enavu.com/tutorials/create-an-amazing-contact-form-with-no-ready-made-plugins/得到了原始教程并修改了它

编辑 在放入一些不同的警报后,我发现它不执行条件语句if(error==false)... 任何想法为什么?

【问题讨论】:

  • 快速浏览,这应该可以正常工作。在关键行中添加警报,看看它在哪里停止或更好地使用 Firebug 或类似的东西对其进行调试,然后让我们知道结果。
  • 是的 - 特别是,我会使用“alert()”或“console.log()”来确保在第二次通过时调用“click”处理程序。
  • 第二次没有调用点击事件。你可以随心所欲地点击按钮,但它什么也没做
  • 很有趣!你能把html也发一下吗?
  • @Spiny 我为上面的表单添加了 HTML

标签: php javascript jquery ajax forms


【解决方案1】:

很可能是#DefaultLocation 字段,因为它是只读的,您在第一次发布后将其重置:

document.getElementById('DefaultLocation').value = "";

并且永远不要将它的价值改变回某物(或者你是吗?) 因此您必须执行以下操作之一:

  1. 不要重置它
  2. 在摆好表格后用一些东西设置它的价值
  3. 根本不验证它,因为它是只读的,并且您将它用作隐藏输入(顺便说一句,这是错误的)!

另外,它可能是您正在谈论的其他“ajax”代码,因此请在此处发布,也可能您在页面上的其他位置有其他字段(元素),其 ID 与表单中的相同。

无论如何,这里有一些提示: 1-正确关闭输入标签(添加 / 到它的末尾):

<input type='text' name='Firstname' id='Firstname' />

2- 确保所有 DIV 和 Ps 都已关闭...因为您似乎在这里有一个打开的 P:

 <p>


 <div id='Add_success' class='success'> The user has been added</div>
 <div id='Alreadythere' class='error'> That user is already in the database</div>
 <div id='Add_fail' class='error'> Sorry, don't know what happened. Try later.</div>
 </p> <---- missing this one
 <p id='cf_submit_p'>

3- 你一直在重新声明错误变量,你不需要这样做:

if(Firstname.length == 0){
    var error = true;
....

只使用 error = true; 而不使用 var 这适用于您要更改其值的所有地方,仅在初始化时使用 var

var error = false;

4- 而不是这个:

$('#AddCaller').attr({'disabled' : 'true', 'value' : 'Adding...' });

使用:

$('#AddCaller').attr({'disabled' : 'disabled', 'value' : 'Adding...' });

5- 如果您使用 DefaultLocation 作为隐藏字段,则不要这样:

 <div style="display:none;">
 <input type='text' name='DefaultLocation' id='DefaultLocation' value= "Sometthing"      readonly=readonly />

 </div>

使用:

<input type="hidden" name="DefaultLocation" id="DefaultLocation" value="Something" />

【讨论】:

  • 我赞成这个答案,但 w3 没有为 disabled 属性指定标准值。 True 只是布尔属性的最佳替代方案。 Microsoft 认为 disabled="disabled" 在 Visual Studio 中是正确的,但这不是必需的。
  • 你说得对——在 HTML5 中,它要么是 disabled、disabled="",要么是 disabled="disabled"。但是,我倾向于不使用 HTML5 作为参考,因为该文档正在开发中。
【解决方案2】:

尝试从使用单击事件处理程序更改为表单的提交事件处理程序

改变这个:$('#AddCaller').click

对此:$('#AddCaller_form').submit

【讨论】:

  • 这是一个很好的答案,我不确定将属性设置为disabled 对事件处理程序有什么作用,可能会丢弃它们?有了这个答案,你就不需要关心了。
【解决方案3】:

disabled属性不要去掉,设置为false。

这一行

$('#AddCaller').removeAttr('disabled').attr(...

应该是

$('#AddCaller').attr('disabled', false).attr(...

【讨论】:

  • 您想删除禁用的属性,因为它的存在表示禁用,无论它具有什么值。烦人。
【解决方案4】:

我假设通过删除和添加属性,元素被删除并被新元素替换,但处理程序没有重新附加。尝试使用$('#AddCaller').live('click', function(){ //code }) 而不是.click()

【讨论】:

    【解决方案5】:

    此函数向 php 发送查询,并可以使用 ajax 从 php 文件返回结果。 我已将 cmets 留作指导。 try & catch 语句的第一部分不需要修改。转到#1 和#2

     function ajaxFunction(){
            var ajaxRequest;  
    
    
            //Browser compatible. keep it as it is 
            try{
                // Opera 8.0+, Firefox, Safari
                ajaxRequest = new XMLHttpRequest();
            } catch (e){
                // Internet Explorer Browsers
                try{
                    ajaxRequest = new ActiveXObject("Msxml2.XMLHTTP");
                } catch (e) {
                    try{
                        ajaxRequest = new ActiveXObject("Microsoft.XMLHTTP");
                    } catch (e){
                        // Something went wrong
                        alert("Your browser broke!");
                        return false;
                    }
                }
            }
            //Browser compatible end
    
    
    
            ajaxRequest.onreadystatechange = function(){
                if(ajaxRequest.readyState == 4){
                       //#2 opional: create functions to return data from your php file
                       $('#resultArea').html(ajaxRequest.responseText);
                }
            }
    
            //#1 Set the form method, filename & query here here
            ajaxRequest.open("GET", "serverTime.php?query=something", true);
            ajaxRequest.send(null); 
        }
    



    示例:

    <input type='submit' value='ajax-submit' onclick='ajaxFunction()' />
    

    【讨论】:

      【解决方案6】:

      快速的 jquery 插件,因为您可以在您网站上的几乎所有 ajax 表单中使用它:

      它将禁用所有可能触发提交事件的字段,并在表单标签上添加一个类,以便您可以应用一些样式,或在提交表单时显示加载消息:

      jQuery.extend(jQuery.fn, {
        formToggle: function (enable){
          return this.each(function(){
            jQuery(this)[(enable ? 'remove' : 'add') + 'Class']('disabled')
            .find(':input').attr('disabled', !enable);
        },
        enable: function(){ return this.formToggle(true); },
        disable: function(){ return this.formToggle(false); }
      }
      

      然后在你的 jq ajax 代码上:

      [...]

      var $form = $(your_form).submit(function(){
        $.ajax({
          type: 'post', 
          url: "/whatever/", 
          data: $form.serialize(), 
          success: function (){ alert ('yay');},
          complete: function(){ $form.enable();},
          error: function(){ alert('insert coin')}
        }
        $form.disable(); 
        return false;
      });
      

      在表单发送/接收数据时正确阻止提交就足够了。 如果您真的很偏执,您可以添加一个检查,以便在用户触发提交和字段被禁用之间不能发送两次: if ($form.is('.disabled')) return false;作为提交处理程序的第一行,但实际上没有必要

      【讨论】:

        【解决方案7】:

        在 Firebug 中设置一些断点并观察它是否到达某个地方。 提交和应用效果后,按钮可能会丢失其单击处理程序。您可能需要在提交后再次分配点击处理程序。

        【讨论】:

          【解决方案8】:

          这不是 100%,而是尝试将代码设置为单独的函数,然后在最后重新绑定 click 事件。

          例子:

          function addCaller(e) {
              // your unchanged code
              $('#AddCaller').click(addCaller(e));
          }
          
          $(document).ready(function(){
              // added an unbind just in case
              $('#AddCaller').unbind('click').click(addCaller(e));
          });
          

          【讨论】:

            【解决方案9】:

            尝试改变这一点: $('#AddCaller').attr({'disabled' : 'true', 'value' : 'Adding...' }); 进入那个: $('#AddCaller').attr({'value' : 'Adding...' });

            这应该可以正常工作。

            【讨论】:

            • 希望在 POST 运行时禁用它。
            猜你喜欢
            • 2011-11-21
            • 1970-01-01
            • 2018-05-25
            • 1970-01-01
            • 2017-07-28
            • 1970-01-01
            • 1970-01-01
            • 2015-02-18
            • 2017-07-27
            相关资源
            最近更新 更多