Question

Consider the following scenario: I have a page that can open a dialog (jquery dialog). This dialog allow the user to update some values or even insert new ones. The user, sometimes, clicks several times on the "Confirm" button, which fires the update or insert as much as the times clicked. The method is fired through an ajax call (jquery ajax), that on success show the user a nice "It's done" message.

On the update scenario, it's fine, even though my server code has to call the update command on database as much times as the method is called. However on the insert situation, my data is submitted several times and several rows are inserted on database. This causes a lot of problems on other areas.

I read about the post-redirect-get pattern which would the ideal solution for my problem. But it only says about a non ajax post. What about when the call to the method is done through an ajax call? How to prevent an user from submitting several times the same thing?

I tried to block the button on the dialog and even though it works, i think is bad solution, since the button may not be blocked all times, specially if the user has some problem on his browser.

Était-ce utile?

La solution 2

Even though Nathan Taylor's solution was possible and correct, i prefered to do something more simple. I created a local boolean that should check if the form was submitted or not. The first time the form is submitted this variable receives true and prevents further submissions. Check the code below:

<script type="javascript">
var isSubmit = false;

$('#myForm').submit(function(){
  //Check if this is the first time the form is submitted
  if(isSubmit === true){
  return false;
}
isSubmit = true;
//Executes the form submission as it should be
});
</script>

Remember to create this isSubmit var on the dialog scope, otherwise you won't be able to submit this form anymore, unless, of course, you change the variable somewhere else.

Autres conseils

Aside from disabling the Save button after the user clicks it (which is a perfectly reasonable solution), another option is to have a unique validation token as part of your form submission which is validated each time the user clicks Save.

When the form view is requested, generate a unique identifier (GUID or similar), store it in the user's session and also pass it to the view. In the view, include the unique identifier as one of the hidden fields submitted with the form. Now, when the form submission is handled, compare the value in the request with the value in the session. If the request and session values match, replace the value in the session with a new unique identifier and perform the database operation. If the request and session values do not match, you will know that the user double-submitted.

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top