StriplingWarrior
StriplingWarrior

Reputation: 156728

How can I cancel a file upload using the jQuery forms plugin

I'm using the jQuery Forms plugin to do an asynchronous file upload. Currently, the only way for the user to abort that upload is to press the "Stop" button on their browser, which may cause other javascript and ajax requests to stop as well. I'd like to provide a cancel button, but I haven't found any way to cancel an upload as it is happening using the API.

Is there a built-in way, or at least a robust hack I can use, to cancel the upload as it occurs?

Upvotes: 3

Views: 4921

Answers (2)

shukshin.ivan
shukshin.ivan

Reputation: 11340

Since Dec 2012 it is possible to access xhr directly:

var form = $('#myForm').ajaxSubmit({ ... });
var xhr = form.data('jqxhr');
....
$('#cancel').on('click', function(){
    xhr.abort();
});

I use it to cancel ajax file upload.

link - https://github.com/malsup/form/issues/221

Upvotes: 1

StriplingWarrior
StriplingWarrior

Reputation: 156728

The ajaxForm method takes all the same options that jQuery.ajax takes, so it is possible to capture the dummy xhr that it produces in a beforeSend handler. The xhr has an abort method that aborts the file upload:

f.ajaxForm({
    beforeSend: function(xhr) {
        cancelBtn.click(xhr.abort);
    }});

Upvotes: 5

Related Questions