kirby
kirby

Reputation: 4041

Form still submits on preventDefault

I am using jQuery to submit form data to a file in the form's action. However, when I submit the form, the browser redirects to the action (comment.php). I don't know why this is because e.preventDefault() should stop the browser's redirection. Ideally, I would like the browser to not redirect and remain on the current page (index.php).

jQuery:

<script type='text/javascript'>
    $('document').ready(function(){
        $('.commentContainer').load('../writecomment.php');
        $('.answerContainer').on('submit', 'form', function(e){
            e.preventDefault();
            var form = $(this).closest('form');
            $.post($(form).attr('action'), 
            $(form).serialize(), 
            function() {
                $('.commentContainer').load('../writecomment.php');
                $('.commentBox').val('');
            }
        });
    });
</script>

HTML Form:

<form method='POST' action='../comment.php'>
    //form contents
</form>

Upvotes: 1

Views: 6223

Answers (1)

Andreas Louv
Andreas Louv

Reputation: 47099

I don't think your selector and on method is working correctly. Try: $('form').on('submit', function(e) { are you sure you have wrapped your form in a element with the class answerContainer??

and then just to be sure don't use $.post use $.ajax:

and this inside an on i the element eg. form not the first selector .answerContainer.

$('document').ready(function(){

    $('.commentContainer').load('../writecomment.php');

    $('.answerContainer').on('submit', 'form', function(event) {
        event.preventDefault();
        var $form = $(this);
        $.ajax({
            "url": $form.attr("action"),
            "data": $form.serialize(),
            "type": $form.attr("method"),
            "response": function() {
                $('.commentContainer').load('../writecomment.php');
                $('.commentBox').val('');
            }
        });
    });
});

Upvotes: 3

Related Questions