Form still submits on preventDefault

前端 未结 1 927
遥遥无期
遥遥无期 2021-01-26 20:56

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

相关标签:
1条回答
  • 2021-01-26 21:56

    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('');
                }
            });
        });
    });
    
    0 讨论(0)
提交回复
热议问题