Ashley Brown Ashley Brown - 2 months ago 6
HTML Question

Why doesn't preventDefault() stop redirect on this form submission?

I've been trying to submit this form with jQuery but I can't seem to stop it from redirecting after I submit it. Where am I going wrong?

My form simplified:

<form action="http://xxxxxxx" method="post" id="myform">
<input type="text" name="my_field">
<a class="last">Submit<a>
</form>


JS:

$('.last').on('click', function() {
if ($('#myform').valid()) {
$('#myform').submit();
}

$('#myform').on('submit', function(event) {
event.preventDefault();

$.getJSON(
this.action + "?callback=?",
$(this).serialize(),
function(data) {
if (data.Status === 400) {
alert(data.Message);
$('#noti').text(error).addClass('notice-error', function() {
$('.last').attr('id', '#contact-us-btn').addClass('button-error').html('Contact us');
});
$('#contact-us-btn').on('click', function() {
zE(function() {
zE.show();
});
});
} else {
console.log(data.Message);
$('#step-3').slideUp(function() {
$('#noti').text(success).addClass('text-success');
$('.next, .previous').fadeOut();
$('.panel.success').slideDown();
});
}
}
)
});
});

Answer

It's not the order, the issue is that the second event was being assign inside the first event function (basically it would be assigned after the click therefore the form submission).

$('.last').on('click', function() {
  if ($('#myform').valid()) {
    $('#myform').submit();
  }
});

$('#myform').on('submit', function(event) {
  event.preventDefault();

  $.getJSON(
    this.action + "?callback=?",
    $(this).serialize(),
    function(data) {
      if (data.Status === 400) {
        alert(data.Message);
        $('#noti').text(error).addClass('notice-error', function() {
          $('.last').attr('id', '#contact-us-btn').addClass('button-error').html('Contact us');
        });
        $('#contact-us-btn').on('click', function() {
          zE(function() {
            zE.show();
          });
        });
      } else {
        console.log(data.Message);
        $('#step-3').slideUp(function() {
          $('#noti').text(success).addClass('text-success');
          $('.next, .previous').fadeOut();
          $('.panel.success').slideDown();
        });
      }
    }
  )
});
Comments