Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

jquery

ajax

forms

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? This is not about which type attribute value is better for the button in this case, but why event handler 1 is better than 2 or vice-versa.

like image 248
lennyklb Avatar asked Nov 04 '16 13:11

lennyklb


1 Answers

A form can be submitted by multiple sources, not only by clicking the submit button (eg: manually invoking $("form").submit() or pressing 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.

like image 187
Alexandru Severin Avatar answered Oct 29 '22 23:10

Alexandru Severin