简体   繁体   中英

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.

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 )

As the previous posters have indicated, you should write an Ajax function to submit the form asynchronously. The form handler would return a message which could be appended to a div on your page. 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:
The code I posted was an example of how you would use Ajax, not a complete solution. 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.

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". 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.

While submitting form you can use AJAX and return false

In AJAX you could get all form values pass to server 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

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.

With jQuery's post function :

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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