3

I'm using the jQuery malsup ajaxForm plugin on a form. I've got a bunch of POST vars that get submitted and this is working fine, I want to use the same post vars to perform an Export to file option. This means using the same form for both submission types.

Because you can't download Files through an AJAX submission, I'm using .unbind('submit').submit() on the form to prevent the previously assigned ajax event handlers from firing.

After this unbinding occurs, I then have to re-run the ajaxForm constructor when the user wants to change the filters using AJAX (not for the export).

Before I invest more time in fixing the edge cases and a couple of bugs, I wondered if there was a cleaner way to do this?

Tr1stan
  • 2,755
  • 1
  • 26
  • 45
  • Dude, you are my hero - I spent 2 hours pulling my hair trying to figure out just how to 'unbind' that stupid (well, not really) ajaxForm. Did you ever find a better way of doing this? – techexpert Jun 17 '12 at 07:54

2 Answers2

1

Use custom events and trigger()!

First, put a radio button on your form to allow the user to switch between AJAX/Export to file. Let's say the name of this field is submitAction

Second, your submit listener acts only to decide what happens next based upon the value of the submitAction radio. This is where you fire the custom events (we define them in step 3):

$('form.specialform').on('submit',function(e){
    e.preventDefault();
    var checked = $(this).closest('[name="submitAction"]').filter(':checked');
    if(checked.val() == 'ajax'){ //ajax!
        $(this).trigger('submitAJAX');
    } else { //export to file!
        $(this).trigger('submitExport');
    }
});

Third, define your custom events with two event listeners:

$('form.specialform').on('submitAJAX',function(e){
    //do AJAX call here
});

$('form.specialform').on('submitExport',function(e){
    //do file export here
});

As you can see, doing it this way allows you to avoid the mess of unbinding and rebinding the same event handlers a bunch of times.

Does that help?

Jonathan Wilson
  • 4,138
  • 1
  • 24
  • 36
0

Thanks a lot to Jonathan for the above answer. We too were faced with similar problem and triggering custom events did the trick for us. Also i would add that if malsup ajaxForm plugin is being used, we should invoke 'ajaxSubmit' instead of ajaxForm as ajaxForm doesn't submit the form.

    $('form.specialForm').on('submitAJAX',function(e) {
        $(this).ajaxSubmit({
           target: '#query_output', 
           beforeSubmit:  showLoading,
           success:       hideLoading
       });
   });
pkr13
  • 107
  • 2
  • 10