简体   繁体   中英

jQuery Ajax submitting form multiple times

I am new to Ajax. I am currently submitting a form into my database using jQuery AJAX but it sends the same data multiple times in my database.

Here's my Ajax code :

$(document).ready(function () {
    var id_js;

    $(document).on('click', '.btn-success', function () {
        id_js = $('#ID_TXT').val();
        $('form').submit(function (e) {
            e.preventDefault();
            e.stopImmediatePropagation();
            $.ajax({
                type: "POST",
                url: 'server.php',
                data: {
                    'Mark': 1,
                    'id': id_js,
                },
                success: function (response) {
                    $('#result').html(response);
                }
            });

            return false;
        });
    });
});

Also I have tried .one() and .stopImmediatePropogation() but still no results

I see both form submit and Ajax call are doing the same work. If you are going to post the data only with AJAX call then form submit is not required.

I hope this works well for you.


$(document).ready(function () {
    function postDataToServer() {
        var id_js = $('#ID_TXT').val();

        $.ajax({
            type: "POST",
            url: 'server.php',
            data: {
                'Mark': 1,
                'id': id_js,
            },
            success: function (response) {
                $('#result').html(response);
            }
        });       
    }

    $(document).on('click', '.btn-success', postDataToServer);
});

The submit handler shouldn't be inside the click handler. Every time you click on the button, it adds another submit handler. So when you finally submit the form, it will submit it as many times as you clicked on the button.

If you want to ensure that the form isn't submitted until you've clicked on the button, add a test in the submit handler.

 $(document).ready(function() { var id_js; $(document).on('click', '.btn-success', function() { id_js = $('#ID_TXT').val(); }); $('form').submit(function(e) { if (id_js !== undefined) { $.ajax({ type: "POST", url: 'server.php', data: { 'Mark': 1, 'id': id_js, }, success: function(response) { $('#result').html(response); } }); } else { alert("You need to click on the success button first"); } return false; }); });

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM