1

I have a button that triggers a GET request for a csv file. The server takes a few seconds to generate the file. While the file is being prepared, I want to disable the download button. What is the best way to achieve this with javascript / jquery?

I have this code that executes asynchronously - ideally this code should run synchronously - but perhaps there are different methods to achieve what I am trying to do?

// download csv:
$('#download-button').click(function(){

    // 1) disable the button:
    $(this).attr('disabled', true);

    // 2) launch the file download on a new page:
    document.target = '_blank';
    document.location = "the-download-url";

    // 3) enable the button (only after download is complete - need help here)
    $(this).attr('disabled', false);
});

Edit

For the backend - I am using django - presently I am returning a table in the database as a csv file like so:

def view_function(response):

    # logic to create csv file:
    ...

    # pack csv file in response:
    with open('/tmp/my-file.csv', 'r+') as file:
        response = HttpResponse(file, content_type='text/csv')
        response['Content-Disposition'] = 'attachment; filename=item_mapping_service.csv'

    return response

I am happy to change the backend code as needed if it helps.

Daniel
  • 3,228
  • 1
  • 7
  • 23
  • Could you share some more info on what endpoint you are hitting or how you are making the request for the csv file? One of the suggestions would be to change you function(){} block to an async function(){} to handle the button click event. You can await the request operation and once it is resolved, enable the button. – deep206 Jul 15 '21 at 18:50
  • Thanks for your comment - I've edited my question - let me know if you need more details. – Daniel Jul 15 '21 at 18:56
  • Have you tried this: https://stackoverflow.com/questions/1106377/detect-when-browser-receives-file-download ? – Albab Jul 15 '21 at 19:04

0 Answers0