PinoyTech.org

CodeIgniter, Kohana, Mootools, jQuery and CSS

Creating A Mootools Plugin for Ajax Form Submissions

Posted by teejay on March 17, 2010

Ajax forms are in right now. I just decided to create a plugin, I've been using for a personal project I am on.

How it works

  • On submission, we stop the event.
  • We send the form via Ajax
  • We check if we received any response
  • An HTML response means there's an error, we don't redirect the page.
  • A non-HTML response means, there are no errors, we redirect the page.

The Mootools Class

var Form_request = new Class({
 Implements: [Events],

 initialize: function(form, destination, update, submit) {
  this.form = document.id(form);
  this.updated = document.id(update);
  this.submit_button = $(submit);
  this.destination = destination;
  this.attach();
 },
 attach: function() {
  this.form.addEvent('submit', function(e) {
   e.stop();
   this.form.set('send', {
    onRequest: function() {
     this.submit_button.set('value', 'Sending...').set('disabled', true);
     this.updated.empty();
    }.bind(this),
    onSuccess: function(data) {
     if ($chk(data)) {
      if (data.test("< /div>")) {
       this.submit_button.set('value', 'Continue').set('disabled', false);
       this.updated.grab(new Element('p', {'html': data}));
      } else {
       window. location = this.destination;
      }
     }
    }.bind(this)
   }).send();
  }.bind(this));
 }
});

Usage

new Form_request('form_id', 'http://where/redirect/to', 'elemnt_to_update_with_errors', 'submit_button_to_enable_disable_on_submission');

Note

A probably better implementations is Form.Request, a Mootools More Plugin.

Categories: Clientside

Tags: mootools, class

No Comments

Comments are not allowed