skip to Main Content

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?

3

Answers


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

    Login or Signup to reply.
  2. 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);
                    }
                });
        })
    });
    
    Login or Signup to reply.
  3. 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);
                }
            });
        })
    });
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search