OrElse
OrElse

Reputation: 9959

Why form is never submitted with Jquery?

My form is

<form id="dataForm">

</form>

the button that is clicked is

<button id="btnAddSave" type="button">
    ButtonText
</button>

and the Jquery used is

$(document).ready(function () {
    $("#btnAddSave").click(function () {
        alert("1");
        $("#dataForm").submit(function (e) {
            alert("2");
            e.preventDefault();
            var form = $(this);

            var url = "/save";

            $.ajax({
                type: "POST",
                url: url,
                data: form.serialize(),
                success: function (data) {
                    alert(data);
                }
            });
        });
    })
});

In the example above, the first alert is displayed, but not the second one. What is going on wrong here? How can i fix it?

Upvotes: 0

Views: 41

Answers (3)

Gecko
Gecko

Reputation: 1344

As discussed in the comments, the submit handler is not firing because it is attached when the click handler fires. You can simply just remove all the submit code as such:

$(document).ready(function () {
    $("#btnAddSave").click(function () {
        alert("1");
        alert("2");

        // e.preventDefault(); -> this does nothinng for a button type button
        var form = $("#dataForm");

        var url = "/save";

        $.ajax({
            type: "POST",
            url: url,
            data: form.serialize(),
            success: function (data) {
                alert(data);
            }
        });
    })
});

Upvotes: 0

Korovjov
Korovjov

Reputation: 533

As I mentioned in comment, this is a working example:

$(document).ready(function () {
    $("#btnAddSave").click(function () {
        alert("1");
            alert("2");
            e.preventDefault();
            var form = $("#dataForm").serialize();

            var url = "/save";

            $.ajax({
                type: "POST",
                url: url,
                data: form,
                success: function (data) {
                    alert(data);
                }
            });
    })
});

Upvotes: 1

balint
balint

Reputation: 3431

Why do you bind two event handlers in each other? Go with .click or .submit, no need for both. The code itself should work.

Upvotes: 3

Related Questions