Skip to content Skip to sidebar Skip to footer

Avoid Form Multiple Submissions And Re-enable When Done

I have a form which allows to view data in a page or download it in csv according to the submit button pressed. Since it's a long database query I want to avoid the user to submit

Solution 1:

When user sees results and then press the browser's back button he will get again the Processing, please wait sentence and no submit buttons (what if he just wants to edit something and make a new query)

The browser is caching the page. You could try resetting the values/removing the loading image in $(document).ready() which should fire when the user presses the back button using the onunload trick: Is there a cross-browser onload event when clicking the back button?

after user is prompted to download the CSV file he keeps on being told to wait...

It won't be possible to detect this without the help of the server. The easiest thing to do would be to "ping" the server via ajax and the server will tell the client if the download was initiated/sent to the user. This can be done by repeatability calling the server every i.e. 3 seconds to see if the download was initiated and if so, reset/hide the loading image and text.

You could use jQuery deferred to help make this easy and of a nice syntax.

jQuery

functiondownloadStarted()
{
  var $def = $.Deferred();

  var check = function() {
     $.get('/ajax/check-download-status', function(response) {
        if (response.started)
        {
          $def.resolve();
        }
        else
        {
          //Check again in 3 secondssetTimeout(check, 3000);
        }
      }, 'json');
  };
    
  check();

  return $def.promise();
}

Usage:

var success = function() { /* reset/hide loading image */ }
$.when(downloadStarted()).then(success);

PHP/Server side

On the server side ajax/check-download-status will look like so:

session_start();
$json['started'] = 0;
if ($_SESSION['download_started']) $json['started'] = 1;
return json_encode($json);

And obviously when your csv file is sent to the client, set $_SESSION['download_started'] to 1.

Solution 2:

Found this:

Detecting the File Download Dialog In the Browser

and this is my code based on it:

html

<form...><fieldset> 
    ...
    <div><inputclass="wait"id="submit"name="submit"type="submit"value="View" /><inputclass="wait"id="submit"name="submit"type="submit"value="Download as CSV" /></div></fieldset></form>

javascript

$(document).ready(function(){
    var cookieCheckTimer;
    var cookieName = 'download_token';
    var $wait = $('.wait');
    var $waitMsg = $('<span>Processing, please wait...</span>').prepend(
        $('<img />').attr('src', '/img/wait.gif').css({
            'vertical-align': 'middle',
            'margin-right': '1em'
        }));
    //add hidden field to forms with .wait submit
    $wait.parent().each(function(){
        $(this).append($('<input />').attr({
            'type': 'hidden',
            'name': cookieName,
            'id': cookieName
        }));
    });
    $wait.click(function(){
        var token = newDate().getTime();
        //set token value
        $('#' + cookieName).val(token);
        //hide submit buttons
        $(':submit').hide();
        //append wait msg
        $(this).after($waitMsg);

        cookieCheckTimer = window.setInterval(function () {
            if ($.cookie(cookieName) == token){
                //clear timerwindow.clearInterval(cookieCheckTimer);
                //clear cookie value
                $.cookie(cookieName, null);
                //detach wait msg
                $waitMsg.detach();
                //show again submit buttons
                $(':submit').show();
            }
        }, 1000);
    });
});

Server side if a download_token key is found in request parameters a cookie with its name and value is set.

Here's my python (pylons) code for a controller's __before__ :

python

cookieName = 'download_token'#set file download coockie if askedif cookieName in request.params:
    response.set_cookie(cookieName,
        #str: see http://groups.google.com/group/pylons-discuss/browse_thread/thread/7d42f3b28bc6f447
        str(request.params.get(self._downloadTokenName)),
        expires=datetime.now() + timedelta(minutes=15))

I set cookie expire time to 15 minutes to not fill up client cookies, you choose an appropriate duration based on time needed by task.

This also will work with browser back button issue as when going back the cookie will be found and buttons restored.

Post a Comment for "Avoid Form Multiple Submissions And Re-enable When Done"