0

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?

asmask
  • 35
  • 2
  • I could put a Boolean variable. If the form is sent you change the value of this variable to true or false, and make a conditional to check its value, depending on the value you send or not – Aks Jacoves Jun 08 '20 at 20:01

2 Answers2

2

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.

Green-Avocado
  • 901
  • 5
  • 20
0

found this solution here

 $("form").submit(function () {
        if ($(this).valid()) {
            $(this).submit(function () {
                return false;
            });
            return true;
        }
        else {
            return false;
    }
});
Ahmed Magdy
  • 1,054
  • 11
  • 16