Search code examples
javascriptjqueryjquery-eventspreventdefault

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!
      } 
      
    }
  });

})

Solution

  • 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
            }
        }
    });