0
$('form.comment_form').submit(function(e) {
    e.preventDefault();
    var $form = $(this);
    $.ajax({
        url : 'inc/process-form.php',
        type: 'POST',
        cache: true,
        data:({
            comment      : $form.find('input[name="comment"]').val(),
            pid          : $form.find('input[name="pid"]').val(),
            post_author  : $form.find('input[name="post_author"]').val(),
            date_comment : $form.find('input[name="date_comment"]').val()
        }),
        success : function(results) {
            $('.show-results').html(results).slideToggle().delay(2000).slideToggle();
            $form[0].reset();
            $('#all-post').load('home.php #all-post li');       
        }
    });
    return false;
});

The code above is my "jQuery+AJAX" for comment form. When I am submitting the comment form, it works fine but when I am submitting it again within a second, it reloads the page.

2
  • Do you get javascript error when you submit form at second time? Commented May 5, 2014 at 7:16
  • I don't get any error, what happen is the fallback php script working at the second submit. It by passed the jQuery Commented May 5, 2014 at 7:24

1 Answer 1

1

You can use unbind method to stop submitting the form again.

Here is the code as a sample :

var $form = $('form');
$form.bind('submit', function(e){
    e.preventDefault();
    ...
    $.ajax({
        ...
        success: function(){
            ...
            $form.unbind('submit').trigger('submit');
        }
    });
});

or you can use the it in other way by using $(document).on("submit", "form", function() { });

sample code :

$(document).ready(function () {
   $(document).on("submit", "form", function() {
        $('#content').fadeOut(100, function () {
            $(this).html('
                <img src="//mywebsite.com/spinner.gif"/>
                <div style="display:inline;color:#1FAEFF">Loading...</div>
           ').fadeIn(100);
        });
        $.get('submit.server', $(this).serialize(), function (data) {
            $('#content').html(data);
        });
        return false;
    });
});
Sign up to request clarification or add additional context in comments.

2 Comments

What was the exact code? and why get 'cause im using post method here
You can use $.post if you want to post the form. $.post('submit.server', $(this).serialize(), function (data) { $('#content').html(data); });

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.