3

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.

0

2 Answers 2

2

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)

Sign up to request clarification or add additional context in comments.

5 Comments

The only thing i have done made it work is, load the js file that contains the code above with the appended html. But its not a good practice i thinks
Maybe I'm focusing on the wrong issue altogether then. What is initFormSubmit. Can you provide more context in the question?
it is a jquery plugin helper
@BijeshShrestha You should add the pastebin to the question. If more people see it they might be able to help.
ok it worked after i cleared the browser's cache ;) and recall the helper after success
0

Try using event.preventDefault at the end of the submit event like this:

$(document).on('submit', form, function (event) { if ($(this).attr('name')) { form.append( $("<input type='hidden'>").attr({ name: $(this).attr('name'), value: $(this).attr('value')}) ); event.preventDefault(); } **}** 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.