Search code examples
jqueryuploadprogress-barjquery-forms-pluginidentify

Access id of ajaxForm element


I need to access the id of the form element with class="ajax-upload-image". I have several of these forms, with the same class, which is why I need to access the id, but it seems like I cannot get the right values using $(this). I need this value in both beforeSend, uploadProgress, and complete.

Is there some way to save a custom variable, or extract it through the data being sent? My current "solution" is to store a global varible with the id last accessed, but that is hardly a solution, since it is possible to use the forms before the previous are done uploading, which mean a change in the global variable.

My stripped code so far (without the global variable):

$('.ajax-upload-image').ajaxForm({
    delegation: true,
    dataType: 'json',

    beforeSend: function() {
        // Some code
    },

    uploadProgress: function(event, position, total, percentComplete) {
        // Some code
    },

    complete: function(data) {
        // Some code
    }
});

Any help is highly appreciated, since I seem to be very stuck at this point.


Solution

  • When you call ajaxSubmit(), you can pass a context: option. All the callbacks will be bound to this context:

    $(".ajax-upload-image").submit(function() {
        $(this).ajaxSubmit({
            context: this,
            ...
        });
    });
    

    You will then be able to use $(this) and this.id in the callbacks to refer to the form that was submitted.