Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
621 views
in Technique[技术] by (71.8m points)

ajax - jQuery submit form without reloading page

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(); 
    });
}); 
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...