I want to intercept a form, check for a condition and if it exists, prevent the default action. Otherwise, I want to pretend no such interception took place. The JavaScript looks something like this.
$("form").submit(function (event)
{
$.ajax
({
url: $(this).attr("action"),
type: $(this).attr("method"),
data: $(this).serialize(),
dataType: "html",
async: false,
success: function (response)
{
if (foo in response) // This is just pseudo code.
{
event.preventDefault();
// bar
}
}
});
});
The problem is that the form is being submitted twice if foo is not found in response and I can’t figure out why. I can assure you that it is a JavaScript issue. If I disable this progressive enhancement, everything works as designed.
EDIT: Adding return false at the end of the code is absolutely incorrectly. I stated that if foo is not found in response I want to pretend no such interception took place. That means I want the page to refresh and do whatever it was going to do.
I am already preventing the default event under very specific circumstances.
EDIT: sillyMunky and alex have touched on my issue. There is definitely a flaw in my design that I’m trying to resolve.
EDIT: I’m looking for help and I have provided code. Downgrading questions and answers without providing feedback is just plain rude.
It appears you are submitting the form via XHR. If so, just call
event.preventDefault()at the top of yoursubmit()function.If you want to natively resubmit the form later in the
successcallback, call the form’s nativesubmit()event, i.e.$('form')[0].submit()(which won’t trigger jQuery’ssubmit()which would cause an infinite loop because of the rehandling of the condition).Using
async: falsewill lock the browser before the request has finished. Don’t do that.