Lennart Kloppenburg Lennart Kloppenburg - 1 year ago 63
Ajax Question

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

Assume this simple HTML form:

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

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:

var data = $(this).serialize();
//Ajax code here

Here, I'd add
to button

2. Attaching an event handler to the button:

var data = $("#settings-form").serialize(); // or this.closest("form").serialize()
//Ajax code here

And here,

My question is: Which option is better and why?

Answer Source

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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download