Search code examples
javascriptphpjqueryajaxcodeigniter-2

Form submit not working after second attempt in jQuery AJAX


I have a form in my project that will be submitted by jQuery AJAX.

The data will be validated on the server side and if the data is invalid it will load the form with validation errors and append that HTML to the div.

On the next form submission attempt, it is directly redirected to the form action URL, i.e. event.preventDefault() is not working.


Here is my code:

initFormSubmit: function () {
                var form = $('form#forum');
                $(document).on('submit', form, function (event) {
                    event.preventDefault();

                    if ($(this).attr('name')) {
                        form.append(
                                $("<input type='hidden'>").attr({
                            name: $(this).attr('name'),
                            value: $(this).attr('value')})
                                );
                    }

                    var formData = form.serialize();

                    $.ajax({
                        type: form.attr('method'),
                        url: form.attr('action'),
                        data: formData,
                        success: function (data) {
                            $('#respond').empty();

                            $('#respond').append(data);
                        }
                    });
                });

            }

data = form with validation error if invalid.


Solution

  • You're not using event delegation correctly. The second parameter you're passing to .on is form, which is a jQuery object.

    For event delegation, the second parameter needs to be a string. Since it is an object, jQuery is assuming that it is meant to be passed in as the data parameter instead of the selector parameter. (If you do console.log(event.data) inside the handler, it should show the form object).

    Simply change the handler to:

    $(document).on('submit', 'form#forum', function (event) {
    

    and make sure to change all the references inside the handler from form to $(this)