TypeError: e.preventDefault is not a function

Viewed 80369

I am new in javascript and jquery. I am using two jquery plugins in this code. One is Jquery form validator and the other is Jquery form ajaxSubmit. With normal ajax submission the code works fine, but now i had to post a file too. So I am using ajaxSubmit. When I run this I get an error "TypeError: e.preventDefault is not a function" on browser console.

Please don't mark this as a duplicate question because answers for other questions on the same topic are not working for me.

<script type="text/javascript">
    $(document).ready(function() {

        $("#addpost").validate({
            rules: {
                subject: "required",
                comment: "required"
            },
            messages: {
                subject: "Please enter a subject",
                comment: "Please enter some details",                   
            },
            submitHandler: function(e){
                e.preventDefault();
                $.ajaxSubmit({
                    url: '/addpost',
                    type: 'post',
                    dataType: 'html',
                    data : $( "#addpost" ).serialize(),
                    success : function(data) {
                        location.reload();
                    }
                });
            }
        });     

    }); 
</script>

Solution for my problem was changing the submithandler as follows:-

submitHandler: function(form){
    $(form).ajaxSubmit({
            url: '/addpost',
            type: 'post',
            dataType: 'html',
            data : $( "#addpost" ).serialize(),
            success : function(data) {
                location.reload();
            }
     });
    return false
}

Hoping this will help someone.

4 Answers

For example in laravel I was using like that and it works. $( "#register-form" ).validate({

    submitHandler: function(form) {
        $.ajaxSetup({
            headers: {
                'X-CSRF-TOKEN': $('meta[name="_token"]').attr('content')
            }
        });

        var formData = new FormData(form);
        $.ajax({
            type:'POST',
            url:'{{route('registerapi')}}',
            data: formData,
            cache: false,
            contentType: false,
            processData: false,
            success:function(data) {
                if ($.isEmptyObject(data.error)) {
                    $(':input','#register-form')
                        .not(':button, :submit, :reset, :hidden')
                        .val('')
                        .prop('checked', false)
                        .prop('selected', false);

                    window.location.href = "{{route('/')}}";

                } else {
                    console.log(data.error);
                }
            }
        });
    }
});
Related