jQuery-多种表单提交触发不相关的多个错误消息 [英] jQuery - Multiple form submission trigger unrelated multiple error messages

查看:88
本文介绍了jQuery-多种表单提交触发不相关的多个错误消息的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的php页面上有几种形式.我正在使用jQuery(& Ajax)处理此页面并显示结果.让我们将表单称为:ToDo和Register表单.我已经将事件提交到两个表格中,以便在提交时进行相应的处理. ToDo表单位于页面顶部,而Register表单位于页面底部.这些表格上方有相应的标记,这些标记在处理表格时显示错误/成功消息. div #result_todo显示提交ToDo表单时获得的错误. div #result显示提交注册表时获得的错误.

I have couple of forms on my php page. I am using jQuery (& Ajax) to process this page and show the results. Let's call the forms as: ToDo and Register forms. I have submit events attached to both the forms so that their corresponding processing takes place on submission. The ToDo form is located towards the top of the page and the Register form is located towards the bottom of the page. There are corresponding tags right above these forms that show the error/success messages when the forms are processed. div #result_todo shows the errors obtained when ToDo form is submitted. div #result shows the errors obtained when Register form is submitted.

实际问题: 假设我尝试提交ToDo表单而不填写任何信息.不出所料,我相关的php文件处理了提交的信息,并在div #result_todo中显示了错误. 在此div中有一个十字图像,当单击该十字图像时,单击后淡出用户显示的整个div #result_todo(也有错误).现在,当我滚动到注册"表单并尝试提交而不填写任何信息时,正如预期的那样,我相关的php文件处理了提交的信息,并在div #result中显示了错误.现在的问题是,即使div #result_todo也会显示其中的错误,而实际上却不应该显示.这是不需要的,因为我只想提交注册"表单,并且只需要向我显示与此表单相关的错误,而不是待办事宜"表单.

The actual problem: Let's say that I tried to submit ToDo form without filling any information. As expected, my related php file processes the submitted info and shows the errors in div #result_todo . There's a cross image located in this div which,when clicked upon, fades away the complete div #result_todo (& it's errors as well)from user display when clicked upon. Now when I scroll to my Register form and try to submit it without filling any info, as expected, my related php file processes the submitted info and shows the errors in div #result. The problem now is that even the div #result_todo shows up along with the errors in it, when in fact it should not. This is unwanted as I wanted to submit only the Register form and I have to be shown only the errors related to this form and not the ToDo form.

为减少编码量,我正在调用该函数以在表单提交的成功事件(?)中显示错误消息.所以我觉得这可能是哪里出了问题.我对jQuery和javascript语言非常陌生,请多多包涵.代码如下:

To reduce the amount of coding, I am calling the function to show the error messages in the success event(?) of the form submission. So I feel maybe that's where something is going wrong. I am very new to jQuery and javascripting, so kindly bear with me. The code is below:

<script src="js/jquery-1.3.2.min.js" type="text/javascript"></script>
<script type="text/javascript">
 function removeElement(divRemove) {
        $(divRemove).fadeOut(1000);
    }

function theResult(data, popuDivDel)    {

    var popuDiv = popuDivDel;

    $(popuDiv).removeClass('success'); //remove the classes to avoid overlapping
    $(popuDiv).removeClass('error'); //remove the classes to avoid overlapping

    //If var success received from the php file is 0, then that means there was an error
    if(data.success == 0) 
        {                       
            $(popuDiv).html(data.message); //attach the message to the div
            $(popuDiv).addClass('error');  //attach the error class to the result div to show the errors
            //Add a link to dismiss the errors
            $(popuDiv).prepend('<a href=\"javascript:;\" onclick=\"removeElement(\''+popuDiv+'\')\"><img src="images/dismiss.png" alt="Dismiss Errors" title="Dismiss Errors" width="20" height="20" align="right" /></a>');
        }                   
    else if(data.success == 1)  //means that our submission was good
        {
            $(popuDiv).html(data.message); //attach the message to the div
            $(popuDiv).addClass('success'); //attach the success class to the result div to show success msg
            setTimeout(function(){ $(popuDiv).fadeOut('slow'); }, 2000); //attach the animated effect as well
        }

}
</script>



<script type="text/javascript">
$(document).ready(function() {

    $().ajaxStart(function() {
        $('#loading').show();
        $('#result').hide();

        $('#loading_todo').show();
        $('#result_todo').hide();
    }).ajaxStop(function() {
        $('#loading').hide();
        $('#result').fadeIn('slow');

        $('#loading_todo').hide();
        $('#result_todo').fadeIn('slow');       
    });


    $('#myForm').submit(function() {
        $.ajax({
            type: 'POST',
            url: $(this).attr('action'),
            data: $(this).serialize(),
            dataType: 'json',
            success: function(data) //trigger this on successful reception of the vars from the php file
               {
                   var popuDiv2 = '#result';

                   theResult(data, popuDiv2);
               }

        })
        return false;
    });



    $('#frm_todo').submit(function() {
        $.ajax({
            type: 'POST',
            url: $(this).attr('action'),
            data: $(this).serialize(),
            dataType: 'json',           
            success: function(data) //trigger this on successful reception of the vars from the php file
               {
                   var popuDivDel = '#result_todo';

                   theResult(data, popuDivDel);
               }

        })
        return false;
    });
})
</script>


<h4>ToDo Form</h4>
<div id="loading_todo" style="display:none;"><img src="images/loading.gif" alt="loading..." /></div>
<div id="result_todo" style="display:none;"></div>

<form id="frm_todo" name="frm_todo" method="post" action="proses2.php">
 <label for="todo">Enter to-do item:</label>
<input type="text" name="todo" id="todo" />
<input type="submit" name="sbt_todo" id="sbt_todo" value="Add Item" />
</form>



<p>&nbsp;</p><p>&nbsp;</p><p>&nbsp;</p>




<h4>REGISTER Form</h4>
<div id="loading" style="display:none;"><img src="images/loading.gif" alt="loading..." /></div>
<div id="result" style="display:none;"></div>
<form id="myForm" method="post" action="proses.php">
    <table>
        <tr>
            <td width="100">Name</td>
            <td>
                <input name="name" size="30" type="text" /><?php echo (isset($error)) ? $error['name'] : ''; ?>
            </td>
        </tr>
        <tr>
            <td>e-mail</td>
            <td>
                <input name="email" size="40" type="text" /><?php echo (isset($error)) ? $error['email'] : ''; ?>
            </td>
        </tr>
        <tr>
            <td>phone</td>
            <td>
                <input name="phone" size="40" type="text" /><?php echo (isset($error)) ? $error['phone'] : ''; ?>
            </td>
        </tr>
        <tr>
          <td>comment</td>
          <td><input name="comment" size="40" type="text" id="comment" /><?php echo (isset($error)) ? $error['comment'] : ''; ?></td>
      </tr>
        <tr>
            <td></td>
            <td>
                <input name="submit" type="submit" id="submit" value="Submit" />
                <input type="reset" value="Reset" />
            </td>
        </tr>
    </table>
</form>



<?php //proses.php
//validation

if (trim($_POST['name']) == '') {
    $error['name'] = '- Name Must Fill';
}
if (trim($_POST['email']) == '') {
    $error['email'] = '- Email Must Fill & Valid Mail';
}
if (trim($_POST['phone']) == '') {
    $error['phone'] = '- Phone must be filled';
}
if (trim($_POST['comment']) == '') {
    $error['comment'] = '- Comment must be filled';
}

if ($error) 
    {
        $success = 0;
        $message = '<b>Error</b>: <br />'.implode('<br />', $error);
    } 
else 
    {
        $success = 1;
        $message = '<b>Thank You For Filling This Form</b><br />';  
    }


print json_encode(array('success' => $success, 'message' => $message)); 
die();
?>

<?php //proses2.php
//validation
    if (trim($_POST['content']) == '') 
    {
        $error['content'] = '- Must Fill Todo';
    }


    if ($error) 
    {
        $success = 0;
        $message = '<b>Error</b>: <br />'.implode('<br />', $error);
        $message .= $error['content'];
    } 
    else 
    {
        $success = 1;
        $message = '<b>Thank You For Filling This Form</b><br />';  
    }



print json_encode(array('success' => $success, 'message' => $message)); 
die();
?>

请向我建议一个可能的解决方案,同时有效利用函数以减少实现共同目标(如显示结果及其相应效果)所需的编码量.

Please suggest me a possible solution to this problem while making an efficient use of the functions to reduce the amount of coding it might require to achieve common objectives (like showing the results with their corresponding effects).

谢谢.

推荐答案

Hiya,快速浏览一下您的代码(我没有对此进行彻底的测试),我有以下评论:

Hiya, just from a quick glance at your code (I haven't testing this thoroughly), I have the following comments:

  • Enter将同时提交两种表格
    • 您可以通过禁用Enter键或以下操作来解决此问题:
    • 删除表单方法(它已经在$ .ajax函数中)
    • 将表单操作移至$ .ajax函数
    • type="button"替换输入type="submit".
    • .submit功能更改为.click,并定位按钮而不是表单.
    • Pressing Enter will submit both forms
      • You could fix this by disabling the Enter key, or the following:
      • Remove the form method (it's already in the $.ajax function)
      • Move the form action into the $.ajax function
      • Replace the input type="submit" with type="button".
      • Change the .submit functions to .click and target the buttons instead of the form.
      • 这些函数在提交任何一种表单时都会显示两种加载消息
      • 将显示加载消息移至.click函数
      • 将皮革的加载和淡入结果移动到.click函数的结尾
      • These functions reveal both loading messages when either form is submitted
      • Move the show loading message into the .click function
      • Move the hide loading and fade in result to the end of the .click function

      就像我之前说过的,我还没有测试过其中的任何一个(我没有安装php服务器),但是我确实知道在按Enter键时两种形式都可以提交.

      Like, I stated before, I haven't tested any of this (I don't have my php server up), but I do know that both forms submit when pressing enter.

      这篇关于jQuery-多种表单提交触发不相关的多个错误消息的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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