0

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 more than once (you know how heavy is users' index finger on left mouse button...) to avoid database overload and also to make user more relaxed...

I wrote this little jQuery code to substitute submit button(s) with a Processing, please wait and the classic animated spinning gif

$(document).ready(function(){
    //preload wait img
    var $waitImg = $('<img />').attr('src', '/img/wait.gif')
    $('.wait').click(function(){
        $(':submit').hide();
        $(this).after($('<span>Processing, please wait...</span>').prepend($waitImg));
    });
});

All works but has some drawbacks:

  • 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)
  • after user is prompted to download the CSV file he keeps on being told to wait...

Solutions could be to detect someway user is back or download stared or another way to tell him work is in progress.

The easier, the better.

neurino
  • 11,500
  • 2
  • 40
  • 63

2 Answers2

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

function downloadStarted()
{
  var $def = $.Deferred();

  var check = function() {
     $.get('/ajax/check-download-status', function(response) {
        if (response.started)
        {
          $def.resolve();
        }
        else
        {
          //Check again in 3 seconds
          setTimeout(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.

Community
  • 1
  • 1
Gary Green
  • 22,045
  • 6
  • 49
  • 75
  • Thanks, I'm implementing the [Detecting the File Download Dialog In the Browser](http://geekswithblogs.net/GruffCode/archive/2010/10/28/detecting-the-file-download-dialog-in-the-browser.aspx) thing which I think could work also for the _back button_ issue. +1 for the [Cross-browser onload event and the Back button](http://stackoverflow.com/questions/158319/cross-browser-onload-event-and-the-back-button) link. – neurino May 11 '11 at 12:42
0

Found this:

Detecting the File Download Dialog In the Browser

and this is my code based on it:

html

<form ...> 
    <fieldset> 
    ...
    <div> 
        <input class="wait" id="submit" name="submit" type="submit" value="View" /> 
        <input class="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 = new Date().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 timer
                window.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 asked
if 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.

neurino
  • 11,500
  • 2
  • 40
  • 63