Programing

클라이언트 측에서 양식이 여러 번 제출되는 것을 방지하는 방법은 무엇입니까?

crosscheck 2020. 9. 9. 07:32
반응형

클라이언트 측에서 양식이 여러 번 제출되는 것을 방지하는 방법은 무엇입니까?


응답이 느리면 제출 버튼을 여러 번 클릭 할 수 있습니다.

이런 일이 발생하지 않도록 어떻게해야합니까?


이미 제출 된 양식에서 제출 이벤트를 비활성화하려면 눈에 잘 띄지 않는 자바 스크립트를 사용하십시오. 다음은 jQuery를 사용하는 예입니다.

편집 : 제출 버튼을 클릭하지 않고 양식을 제출하는 문제를 수정했습니다. 고마워, 이치 반.

$("body").on("submit", "form", function() {
    $(this).submit(function() {
        return false;
    });
    return true;
});

asp mvc 3 unobtrusive validation과 함께 vanstee의 솔루션시도 했으며 클라이언트 유효성 검사가 실패하면 코드가 계속 실행되고 양식 제출이 영구적 으로 비활성화됩니다. 필드를 수정 한 후 다시 제출할 수 없습니다. (bjan의 의견 참조)

그래서 vanstee의 스크립트를 다음과 같이 수정했습니다.

$("form").submit(function () {
    if ($(this).valid()) {
        $(this).submit(function () {
            return false;
        });
        return true;
    }
    else {
        return false;
    }
});

클라이언트 측 양식 제출 제어는 onsubmit 핸들러가 제출 버튼을 숨기고 로딩 애니메이션으로 대체함으로써 매우 우아하게 달성 할 수 있습니다. 이렇게하면 사용자가 자신의 행동 (클릭)이 발생한 지점에서 즉각적인 시각적 피드백을받을 수 있습니다. 동시에 양식이 다른 시간에 제출되는 것을 방지합니다.

XHR을 통해 양식을 제출하는 경우 제출 오류 (예 : 시간 초과)도 처리해야합니다. 사용자 양식 다시 제출 해야 하므로 제출 단추를 다시 표시해야합니다 .

또 다른 메모에서 llimllib는 매우 유효한 지점을 제시합니다. 모든 양식 유효성 검사는 서버 측에서 발생해야합니다. 여기에는 여러 제출 확인이 포함됩니다. 클라이언트를 신뢰하지 마십시오! 자바 스크립트가 비활성화 된 경우에만 해당되는 것은 아닙니다. 모든 클라이언트 측 코드를 수정할 수 있음을 명심해야합니다. 상상하기는 다소 어렵지만 서버와 대화하는 html / javascript가 반드시 작성한 html / javascript는 아닙니다.

llimllib가 제안한대로 해당 양식에 대해 고유 한 식별자로 양식을 생성하고 숨겨진 입력 필드에 넣습니다. 그 식별자를 저장하십시오. 양식 데이터를 수신 할 때 식별자가 일치 할 때만 처리합니다. (또한 추가 보안을 위해 식별자를 사용자 세션에 연결하고 일치시킵니다.) 데이터 처리 후 식별자를 삭제합니다.

물론 가끔 양식 데이터가 제출되지 않은 식별자를 정리해야합니다. 그러나 아마도 귀하의 웹 사이트는 이미 일종의 "가비지 수집"메커니즘을 사용하고있을 것입니다.


<form onsubmit="if(submitted) return false; submitted = true; return true">

이를 수행하는 간단한 방법은 다음과 같습니다.

<form onsubmit="return checkBeforeSubmit()">
  some input:<input type="text">
  <input type="submit" value="submit" />
</form>

<script type="text/javascript">
  var wasSubmitted = false;    
    function checkBeforeSubmit(){
      if(!wasSubmitted) {
        wasSubmitted = true;
        return wasSubmitted;
      }
      return false;
    }    
</script>

클릭 직후 제출 버튼을 비활성화하십시오. 유효성 검사를 올바르게 처리해야합니다. 또한 모든 처리 또는 DB 작업을위한 중간 페이지를 유지하고 다음 페이지로 리디렉션합니다. 이렇게하면 두 번째 페이지를 새로 고침해도 다른 처리가 수행되지 않습니다.


진행률 표시 줄이나 스피너를 표시하여 양식이 처리 중임을 나타낼 수도 있습니다.


현재 시간을 해시하고 양식에 숨겨진 입력으로 만듭니다. 서버 측에서 각 양식 제출의 해시를 확인하십시오. 이미 해당 해시를 받았다면 반복 제출이있는 것입니다.

편집 : 자바 스크립트에 의존하는 것은 좋은 생각이 아니므로 모든 사람들이 계속해서 그 아이디어를 찬성 할 수 있지만 일부 사용자는이를 활성화하지 않을 것입니다. 정답은 서버 측에서 사용자 입력을 신뢰하지 않는 것입니다.


JQuery를 사용하여 다음을 수행 할 수 있습니다.

$('input:submit').click( function() { this.disabled = true } );

&

   $('input:submit').keypress( function(e) {
     if (e.which == 13) {
        this.disabled = true 
     } 
    }
   );

질문에 'javascript'태그를 붙인 것을 알고 있지만 여기에 자바 스크립트에 전혀 의존하지 않는 해결책이 있습니다.

PRG 라는 웹앱 패턴 이며 여기에 이를 설명 하는 좋은 기사 가 있습니다.


다음과 같이 간단하게 여러 제출을 방지 할 수 있습니다.

var Workin = false;

$('form').submit(function()
{
   if(Workin) return false;
   Workin =true;

   // codes here.
   // Once you finish turn the Workin variable into false 
   // to enable the submit event again
   Workin = false;

});

클라이언트 측에서는 @vanstee 및 @chaos에서 제공하는 방법과 같이 자바 스크립트 코드로 양식이 제출되면 제출 버튼을 비활성화해야합니다.

그러나 네트워크 지연이나 자바 스크립트 사용이 불가능한 상황에 대한 문제가있어이를 방지하기 위해 JS에 의존해서는 안됩니다.

So, on the server-side, you should check the repeated submission from the same clients and omit the repeated one which seems a false attempt from the user.


You can try safeform jquery plugin.

$('#example').safeform({
    timeout: 5000, // disable form on 5 sec. after submit
    submit: function(event) {
        // put here validation and ajax stuff...

        // no need to wait for timeout, re-enable the form ASAP
        $(this).safeform('complete');
        return false;
    }
})

The most simple answer to this question as asked: "Sometimes when the response is slow, one might click the submit button multiple times. How to prevent this from happening?"

Just Disable the form submit button, like below code.

<form ... onsubmit="buttonName.disabled=true; return true;">
  <input type="submit" name="buttonName" value="Submit">
</form>

It will disable the submit button, on first click for submitting. Also if you have some validation rules, then it will works fine. Hope it will help.


The simpliest and elegant solution for me:

function checkForm(form) // Submit button clicked
{
    form.myButton.disabled = true;
    form.myButton.value = "Please wait...";
    return true;
}

<form method="POST" action="..." onsubmit="return checkForm(this);">
    ...
    <input type="submit" name="myButton" value="Submit">
</form>

Link for more...


Use this code in your form.it will handle multiple clicks.

<script type="text/javascript">
    $(document).ready(function() {
        $("form").submit(function() {
            $(this).submit(function() {
                return false;
            });
            return true;
        });     
    }); 
</script>

it will work for sure.


the best way to prevent multiple from submission is this just pass the button id in the method.

    function DisableButton() {
        document.getElementById("btnPostJob").disabled = true;
    }
    window.onbeforeunload = DisableButton; 

To do this using javascript is bit easy. Following is the code which will give desired functionality :

$('#disable').on('click', function(){
    $('#disable').attr("disabled", true);
  });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button id="disable">Disable Me!</button>


Most simple solutions is that disable the button on click, enable it after the operation completes. To check similar solution on jsfiddle :

[click here][1]

And you can find some other solution on this answer.


This works very fine for me. It submit the farm and make button disable and after 2 sec active the button.

<button id="submit" type="submit" onclick="submitLimit()">Yes</button>

function submitLimit() {
var btn = document.getElementById('submit')
setTimeout(function() {
    btn.setAttribute('disabled', 'disabled');
}, 1);

setTimeout(function() {
    btn.removeAttribute('disabled');
}, 2000);}

In ECMA6 Syntex

function submitLimit() {
submitBtn = document.getElementById('submit');

setTimeout(() => { submitBtn.setAttribute('disabled', 'disabled') }, 1);

setTimeout(() => { submitBtn.removeAttribute('disabled') }, 4000);}

Just to add to the possible answers without bypassing browser input validation

$( document ).ready(function() {
    $('.btn-submit').on('click', function() {
        if(this.form.checkValidity()) {
            $(this).attr("disabled", "disabled");
            $(this).val("Submitting...");
            this.form.submit();
        }
    });
});

This allow submit every 2 seconds. In case of front validation.

$(document).ready(function() {
    $('form[debounce]').submit(function(e) {
        const submiting = !!$(this).data('submiting');

        if(!submiting) {
            $(this).data('submiting', true);

            setTimeout(() => {
                $(this).data('submiting', false);
            }, 2000);

            return true;
        }

        e.preventDefault();
        return false;
    });
})

An alternative to what was proposed before is:

jQuery('form').submit(function(){
     $(this).find(':submit').attr( 'disabled','disabled' );
     //the rest of your code
});

참고URL : https://stackoverflow.com/questions/926816/how-to-prevent-form-from-submitting-multiple-times-from-client-side

반응형