JQuery submit form without reloading page

2019-02-16 16:17发布

问题:

I'm not very familiar with JQuery. I'm trying to make a form that is submitted in the background without reloading page.

I have a hidden div which shows and hides on click, inside the div there's a form.

I have two problems:

1) When the form validation fails, the form is still submitted. I tried to put validation and submission codes in condition if(validation == valid) { $.ajax.... } but it does not work properly.

2) After the form is submitted the div automatically hides, so successful message cannot be seen.

Here's the code:

$().ready(function() { 

    // validate the form when it is submitted, using validation plugin.
    var validator = $("#contactform").validate({
        errorContainer: container,
        errorLabelContainer: $(),
    onkeyup: false,
    onclick: false,
    onfocusout: false,
    errorPlacement: function (error, element) { 
error.insertBefore(element);    
}   
    });
});

$(function() {

    //this submits a form
$('input[type=submit]').click(function() {
        $.ajax({
            type: "POST",
            url: "contact.php",
            data: $("#contactform").serialize(),
            beforeSend: function() {
                $('#result').html('<img src="loading.gif" />');
            },
            success: function(data) {
                $('#result').html(data);
            }

        })
    })
})


//this shows and hides div onclick
$(document).ready(function(){   
        $(".slidingDiv").hide(); 
        $(".show_hide").show(); 
    $('.show_hide').click(function(){ 
    $(".slidingDiv").slideToggle(); 
    });
}); 

回答1:

Rather than bind to the click event (input[type=submit]) you should bind to the submit event for the form.

$("form").on("submit", function (e) {
    e.preventDefault();

I'm also not sure about the validation. If it runs asynchronously, a callback is required. If it runs synchronously, when does it get triggered? It seems like it should be done when the form is submitted unless your validation plugin does that on its own:

$("form").on("submit", function (e) {
    e.preventDefault();
    if ($(this).validate(options)) {
        $.ajax

Using e.preventDefault will prevent reload and should allow your success div to display.



回答2:

1) use event.preventDefault(); to keep the form from submitting -http://api.jquery.com/event.preventDefault/

2) there isn't anything in the given script that should becausing #result to hide... but you can try $('#result').show() and see if that brings it back



回答3:

Please check which jquery version you are using because in after jquery 1.8.2 "success" function from jquery ajax is deprecated.

Use e.preventDefault() to prevent actual submit event.