简体   繁体   中英

Prevent multiple Javascript execution for submit function

I am using the following code to allow users to submit content to an online board:

$('form').submit(function(){
            var form = $(this);
            var name =  form.find("input[name='name']").val();
            var code =  form.find("input[name='code']").val();
            var content =  form.find("input[name='content']").val();

            if (name == '' || content == '')
                return false;

            $.post(form.attr('action'), {'name': name, 'code' : code, 'content': content}, function(data, status){
                $('<li class="pending" />').text(content).prepend($('<small />').text(name)).appendTo('ul#messages');
                $('ul#messages').scrollTop( $('ul#messages').get(0).scrollHeight );
                form.find("input[name='content']").val('').focus();
            });
            return false;
        });

Unfortunately, if a user rapidly presses enter or rapidly clicks the send button, the code will execute multiple times and their message will be sent multiple times.

How can I modify my code to prevent this multiple execution?

A simple client-side fix would be to create a local variable that tracks whether or not anything has been submitted and have the function only execute if false.

var submitted = false;

$('form').submit(function(){
            var form = $(this);
            var name =  form.find("input[name='name']").val();
            var code =  form.find("input[name='code']").val();
            var content =  form.find("input[name='content']").val();

            if (name == '' || content == '')
                return false;

            if (submitted)
                return false;

            submitted = true;

            $.post(form.attr('action'), {'name': name, 'code' : code, 'content': content}, function(data, status){
                $('<li class="pending" />').text(content).prepend($('<small />').text(name)).appendTo('ul#messages');
                $('ul#messages').scrollTop( $('ul#messages').get(0).scrollHeight );
                form.find("input[name='content']").val('').focus();
            });
            return false;
        });

A better solution would be to send a unique token for the transaction to the client and have the client send it along with the request. You could have server-side coded to verify that the token has only been used once.

found this solution here

 $("form").submit(function () {
        if ($(this).valid()) {
            $(this).submit(function () {
                return false;
            });
            return true;
        }
        else {
            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