Lennart Kloppenburg Lennart Kloppenburg - 28 days ago 7
Ajax Question

Should I catch button click or form submit when using jQuery and AJAX?

Assume this simple HTML form:

<form id="settings-form">
<label>
Input data:
<input name="data"/>
</label>
<button id="submit-btn">Submit</button>
</form>


I want to submit this form using jQuery and AJAX, so the page will not be refreshed. You can do this in at least these two ways:

1. Attaching an event handler to the actual submission of the form:

$("#settings-form").submit(function(event){
event.preventDefault();
var data = $(this).serialize();
//Ajax code here
});


Here, I'd add
type='submit'
to button
submit-btn
.

2. Attaching an event handler to the button:

$("#submit-btn").click(function(){
var data = $("#settings-form").serialize(); // or this.closest("form").serialize()
//Ajax code here
});


And here,
submit-btn
gets
type='button'


My question is: Which option is better and why?

Answer

A form can be submitted by multiple sources, not only by clicking the submit button (eg: manually invoking $("form").submit() or clicking Enter).

Using the first option assures you of catching all possible submits on that form while the second option only blocks the submit when clicking the button. Its up to you to decide which one you need.

In terms of performance there is no difference.

Comments