Search code examples
mootools

submit form using mootools


I have made a class that handles load and submit of a html form. See code below

ND.Form = new Class({
    //--- Implements options og events.
    Implements: [Options, Events],

    //--- Options.
    options: {
        url: '',
        injectTo: ''
    },

    //--- Initialize the class.
    initialize: function (panel, options) {
        //--- Set options
        this.setOptions(options);
        this.panel = panel;
        this.loadForm();
    },

    loadForm: function () {
        var req = new Request.HTML({
            url: this.options.url,
            method: 'get',
            onSuccess: function (html) {
                $(this.options.injectTo).empty();
                $(this.options.injectTo).adopt(html);
                var formId = $(this.options.injectTo).getFirst('form').get('id');
                $(formId).addEvent('submit', function (e) {
                    e.stop();
                    this.submitForm(formId);
                } .bind(this));
            } .bind(this)
        }).send();
    },

    submitForm: function (formId) {
        $(formId).set('send', {
            onSuccess: function (resp) {
                this.panel.loadContent();
                if (resp != null) {
                    $('lbl_error').empty();
                    $('lbl_error').setStyles({ 'display': 'block', 'color': 'red' }).set('html', resp);
                }
            }.bind(this),

            onFailure: function (resp) {
                if (resp != null) {
                    $('lbl_error').empty();
                    $('lbl_error').setStyles({ 'display': 'block', 'color': 'red' }).set('html', resp);
                }
            }
        });
        $(formId).send();
    }
});

And it all works just fine, exept that when i push the save button more than ones the "this.panel.loadContent();" in the "submitForm: function (formId)" fires the same x amount of times I have pushed the button, how can i prevent this ?

/Martin


Solution

  • Starting from mootools 1.3 "set('send')" adds another one event. So You need to write:

    $('myForm').set('send', {
        onSuccess: function (html) {},
        onFailure: function(xhr){}
    }).addEvent('submit', function(e){
        e.stop();
        this.send();
    });
    

    instead of:

    $('myForm').addEvent('submit', function(e){
        e.stop();
        this.set('send', {
            onSuccess: function (html) {},
            onFailure: function(xhr){}
        });
    }).send();
    

    Then Request will be sent only once each time when You handle form.