Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I cancel a file upload started by ajaxSubmit() in jQuery?

I have code similar to the following:

UploadWidget.prototype.setup_form_handling = function() {
    var _upload_widget = this;
    $('form#uploader')
    .unbind('trigger-submit-form')  // This might be our company's own method
    .bind('trigger-submit-form', function() {
        var $form = $(this);
        $form.ajaxSubmit({
            dataType: 'json',
            success: function(data, status, xhr, form) {
                // ...
            },
            error: function(xhr, status, errorThrown) {
                // ...
            }
        });
        return false;
    });
};

Is there a way to use, say, the reset button of the form to cancel the upload process? Or would I have to navigate to the current page (refresh) in order to stop everything?

I tried making a variable stored by the UploadWidget object that stores the jqXHR value (and calling var _upload_widget.jqXHR = $form.ajaxSubmit({ ... });), but I don't think I'm doing it right.

like image 390
TerranRich Avatar asked May 15 '12 13:05

TerranRich


2 Answers

Unlike jQuery.ajax(), ajaxForm() and ajaxSubmit() of the jQuery form plugin do not return the jqXHR object. There are other ways to get the jqXHR object, though:

data() method on the form object (easiest way)

ajaxSubmit() returns the form object. You can call the data() method on this form object to get the XHR object:

var form = $('#myForm').ajaxSubmit({ ... });
var xhr = form.data('jqxhr');

Then call xhr.abort() when you want to abort the upload.

This functionality was added in December 2012; see issue 221. (shukshin.ivan's answer was the first to point this out.)

beforeSend callback (for jQuery Form versions before December 2012)

In addition to the options listed in the jQuery form plugin site, ajaxForm() and ajaxSubmit() will also take any of the jQuery.ajax() options. One of the options is a beforeSend callback, and the callback signature is beforeSend(jqXHR, settings).

So, specify a beforeSend callback function, and the jqXHR object will be passed in as the first parameter of that callback. Save that jqXHR object, and then you can call abort() on that jqXHR object when you want to abort the upload.

like image 61
S. Kirby Avatar answered Nov 17 '22 08:11

S. Kirby


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();
});

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

like image 23
shukshin.ivan Avatar answered Nov 17 '22 08:11

shukshin.ivan