2

I want to validate a form with parsley.js, then submit via jQuery.post, which requires preventing the default form submission, but it's not working as expected.

The docs for form:submit say:

Triggered when after a form validation succeeds and before the form is actually submitted. Return false to interrupt submission.

However, I can't get that to work... the following code updates the #alert element, but then submits the form via the default browser level request. The $.post call doesn't seem to be performed.. it's never received by the server anyway.

$('.contact-form form').parsley().on('form:submit', function() {
  $('#alert')
    .text('Sending...')
  $.post({
    url: '/contact',
    data: form.serialize(),
    success: function() {
      $('#alert')
        .text('Message successfully sent.')
    },
    error: function() {
      $('#alert')
        .removeClass('alert-success')
        .addClass('alert-danger')
        .text([
          'Sorry, a server error has occurred. ',
          'Your message was not sent.'
        ].join())
    }
  })
  return false
})

The following works as expected, validation is performed but the form is not submitted

$('.contact-form form').parsley().on('form:submit', function() {
  return false
}

I've tried things like this to no avail:

$('.contact-form form').parsley().on('form:submit', function(formInstance) {
  formInstance.submitEvent.preventDefault()
}

So I'm stumped...

This issue is different to Preventing form submission after validation by parsley.js which relates to binding jQuery's submit method to an input element instead of form.

Community
  • 1
  • 1
Mr5o1
  • 1,698
  • 1
  • 15
  • 20
  • Have you tried `formInstance.preventDefault()`? – StudioTime Jul 13 '16 at 11:47
  • yes I've tried `formInstance.preventDefault()` Also the possible duplicate you linked relates to jQuery's `.submit` event being bound to an `input` element rather than the `form`. So mine is not the same issue. – Mr5o1 Jul 13 '16 at 12:06

1 Answers1

2

There has to be an error in the code before the return false that interrupts the function and thus never gets to return properly?

Marc-André Lafortune
  • 78,216
  • 16
  • 166
  • 166