Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery override event.preventDefault()

I have a form that, when submitted, goes through the usual e.preventDefault() and sends an ajax request instead. However, if this ajax request returns a certain condition, I want the form to be submitted normally. How do I achieve this?

// Submit handler
$(".reserveer_form").submit(function(event){
  event.preventDefault();

  $.ajax({
    url: $(this).attr("action"),
    data: $(this).serialize(),
    success: function(data) {
      if($(".messagered",data).length > 0){
        var errors = $(".messagered",data);
        $(".gegevens").before(errors);
      } else {
          // SUBMIT THE FORM!
      } 
      
    }
  });

})
like image 380
Bart Zweers Avatar asked Sep 13 '26 05:09

Bart Zweers


2 Answers

Invoke the native submit method on the form, so that it doesn't trigger the jQuery handler.

$.ajax({
    context: this, // <-- set the context.
    url: $(this).attr("action"),
    data: $(this).serialize(),
    success: function (data) {
        if ($(".messagered", data).length > 0) {
            var errors = $(".messagered", data);
            $(".gegevens").before(errors);
        } else {
            this.submit(); // <-- submit the form
        }
    }
});

Since your comment says you change a form variable, you could start your submit handler by checking that same form variable. If it is changed, just return true. If not, continue with the current handler.

like image 21
Niet the Dark Absol Avatar answered Sep 14 '26 19:09

Niet the Dark Absol



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!