简体   繁体   English

如何避免在提交表单时重新加载页面,并且还显示一小段文字“成功注册”

[英]How can I keep the page from reloading on form submit, and also show a small text saying “successfully registered”

Im trying to keep the page from reloading, and I want to show a small message somewhere in the form saying "Successfully registered" when I submit the form. 我试图阻止页面重新加载,并且我想在提交表单时在表单的某处显示一条小消息,说“已成功注册”。 I could do this by returning false but the inputs from the user would not be posted into my db. 我可以通过返回false来做到这一点,但是来自用户的输入将不会发布到我的数据库中。

Thank you in advance 先感谢您

Here is my code: 这是我的代码:

        <script>

    function validate(form) {
        fail  = validateName(form.name.value)
        fail += validateEmail(form.email.value)
        fail += validateCity(form.city.value)
        if (fail == "") { 
   alert("You have been successfully registered."); return true }
        else { 
   document.getElementById('errors').innerHTML = fail;}
   return false
}

        function validateName(field) {
            if (field == "") return "No name was entered.<br/>"
            else if (field.length < 3) return "Name must be at least 3 characters.<br/>"
            else if (!/[a-zA-Z ]/.test(field)) return "Name can only have alphabetical characters.<br/>"
            return ""
            }
        function validateEmail(field) {
            if (field == "") return "No email was entered.<br/>"
            else if (!((field.indexOf(".") > 0) && (field.indexOf("@") > 0)) || /[^a-zA-Z0-9.@_-]/.test(field)) return "The email address is invalid.<br/>"
            return ""
            }
        function validateCity(field) {
            if (field == "") return "No city was entered.<br/>"
            else if (field.length < 3) return "City must be at least 3 characters.<br/>"
            else if (!/[a-zA-Z ]*$/.test(field)) return "City can only have alphabetical characters.<br/>"
            return ""
            }

    </script>


<form action="<?php echo $editFormAction; ?>" name="subscribe" onSubmit="return validate(this)" id="subscribe" method="POST" autocomplete="off">
<div id="errors"></div>
<input name="name" required pattern="[a-zA-Z ]*$" title="Please enter only alphabetic characters" type="text" id="name" placeholder="Your name"/>


<input name="email" required id="email" type="email" title="Please enter your email address" placeholder="Your email address"/>

<input name="city" required pattern="[a-zA-Z ]*$" title="Please enter only alphabetic characters" id="city" placeholder="Your city"/>

<div id="buttons">
            <input type="reset" name="reset" id="resetbtn" class="resetbtn" value="Reset">

            <input type="submit" name="submit" id="submitbtn" class="submitbtn" tabindex="7" value="Submit this!">

            <br style="clear:both;">
        </div>
<input type="hidden" name="MM_insert" value="subscribe">
  </form>

!( https://docs.google.com/file/d/0B69C1JAAohvcYmIyOFdZRGlPRFk/edit?usp=sharing ) !( https://docs.google.com/file/d/0B69C1JAAohvcYmIyOFdZRGlPRFk/edit?usp=sharing

As the previous posters have indicated, you should write an Ajax function to submit the form asynchronously. 如前所述,您应该编写一个Ajax函数来异步提交表单。 The form handler would return a message which could be appended to a div on your page. 表单处理程序将返回一条消息,该消息可以附加到页面的div上。 Here is an example: 这是一个例子:

$(function() {

    $('#submitbtn').click(function(event) {
        event.preventDefault();
        var form = $(this).closest('form'),
            action = form.attr('action');
        $.post(action, form.serialize(), function(data) {
            $('#form-message').html(data);
        })
    });

}); 

Update based on OP's reply: 根据OP的回复进行更新:
The code I posted was an example of how you would use Ajax, not a complete solution. 我发布的代码只是有关如何使用Ajax的示例,而不是完整的解决方案。 To make it a complete solution you can combine your original code with the code I posted so that the form submission only triggers if the form passes your validation routine. 为了使其成为一个完整的解决方案,您可以将原始代码与我发布的代码结合使用,以便仅当表单通过您的验证例程时才触发表单提交。 The validation routine would come after event.preventDefault(), which is what stops the form from immediately submitting. 验证例程将在event.preventDefault()之后,这将阻止立即提交表单。

I would create an array for your error messages. 我会为您的错误消息创建一个数组。 Each time a required field is missing you can add an error to the array. 每次缺少必填字段时,都可以向阵列添加错误。 At the end of the validation routine you can check the size of the array. 在验证例程结束时,您可以检查数组的大小。 If it is empty, meaning there are no errors, you would submit the form. 如果为空,则表示没有错误,请提交表格。 If it contains one or more errors you would not submit the form. 如果包含一个或多个错误,则不会提交该表格。 Instead, you would print the errors to the screen. 相反,您可以将错误打印到屏幕上。

My code example proposed that the backend form handler returns data containing a status message to display to the user. 我的代码示例建议后端表单处理程序返回包含状态消息的数据以显示给用户。 For example "Thanks for registering!" 例如“谢谢注册!” or "Oops, something went wrong! Please try again." 或“糟糕,出了点问题!请重试。” The status message would be appended to a div with an ID of "form-message". 状态消息将附加到ID为“ form-message”的div上。 You would have to add a return statement to your backend form handler and add a similar div element to your markup in order to create that functionality. 您必须将return语句添加到后端表单处理程序,并在标记中添加类似的div元素,才能创建该功能。

While submitting form you can use AJAX and return false 提交form您可以使用AJAX并返回false

In AJAX you could get all form values pass to server script AJAX您可以将所有form值传递到服务器script

This is what you have to do, 这就是你要做的

<form id="formID" onsubmit="return mformPost('your_php_action.php', '#formID');">
    <input type="text" name="test" id="test" value=""/>
</form>

In AJAX AJAX

function mformPost(destinationUrl, formID) {

    var formData = $(formID).serialize(); // serialize your form data
    $.ajax({
        type: 'POST',
        url: destinationUrl,
        data: formData,
        cache: true,
        async:false,
        error: function(error) {
            alert(error.responseText + error.responseStatus);
        },
        success: function(data){ // return data from your php file
            if(data){
                alert('Successfully registered');
            }

        }
    });
    return false;
}

If you want the page to not reload, don't use a form with a submit action -- use AJAX to send the data to a separate PHP script instead, and have the browser launch a notification or popup in the callback function. 如果不希望重新加载页面,请不要使用带有提交操作的表单-而是使用AJAX将数据发送到单独的PHP脚本,并让浏览器在回调函数中启动通知或弹出窗口。

With jQuery's post function : 使用jQuery的post函数

$("#submitbtn").click(function() { 
    $.post("yourphpscript.php", {name: $("#name").val(), email: $("#email").val(), city: $("#city").val() }, 
    function(){
        $("#submitbtn").after("<p>Successfully registered.</p>");        
    });
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM