Search code examples
ajaxasp.net-mvcpost-redirect-get

Implementing post-redirect-pattern on ajax scenario


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.


Solution

  • 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.