Program a Pattern (MooTools)

Reusable example. Using a class to create a generic updater.

by Piotr Zalewa

HTML

<form id='myForm' method='post' action='/ajax_html_echo/'>
    <input type='text' name='html' value='Something to respond' />
    <input type='submit' />
</form>
<p id='myContainer'></p>

CSS

#myContainer { 
    margin-top: 10px;
    color: navy; 
    font-weight: bold;
}

JavaScript

var FormUpdater = new Class({
    initialize: function(form, container, options) {
        this.form = $(form);
        this.container = $(container);
        this.request = new Request(options);
        this.request.addEvent('success', this.onComplete.bind(this));
        this.attach();
    },
    attach: function(){
        this.form.addEvent('submit', this.send.bind(this));
    },
    send: function(evt){
        if (evt) evt.preventDefault();
        this.request.send({
            url: this.form.get('action'),
            data: this.form
        });
    },
    onComplete: function(responseTxt){
        this.container.set('html', responseTxt);
    }
});
FormUpdater.Append = new Class({
    Extends: FormUpdater,
    onComplete: function(responseTxt){
        this.container.adopt(
            new Element('div', {html: responseTxt})
        );
    }
});

window.addEvent('domready', function() {
    new FormUpdater.Append($('myForm'), $('myContainer'));
});