I have an AJAX form I'm setting up, using an <input type="button">
with a jQuery .click action being set.
The problem is, because there is no <input type="submit"
> in the form, the form doesn't submit in a traditional way, so form validators don't always work, and pressing the enter button does nothing.
If I DO add a submit input, when it's clicked (or enter is hit, etc.), the page reloads as if it is not an AJAX form.
What am I missing here?
Use a submit button. The submit button will be more compatible in terms of default browser behavior, such as pressing enter. Then, on the submit event, just cancel the form submission and run your AJAX code.
<form onsubmit="return false;">
<!--Blah Blah Blah-->
<input type="submit">
</form>
If you're using jQuery, you can use a more "clean" method
$('#form_id').bind('submit',function(e) {
e.preventDefault(); //Will prevent the submit...
//Add additional code here
});
Rather change form's submit
behaviour and keep your <input type="submit">
button as well:
$("form").submit(function(e){
e.preventDefault();
// do ajax submition
$.ajax({
url: "SomeURL",
type: "POST",
data: $(this).serializeArray(),
success: function(data, status, xhr) {
// do the success stuff
},
error: function(xhr, status err) {
// do the error stuff
}
});
});
Advantage: The good thing is this will work in all cases when you hit ENTER on any of the form's input elements or click the submit button. It will always work without exception.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With