1
\$\begingroup\$

I wrote an AJAX Form Creator (in the form of an js object constructor) that takes a form and a callback. I am a decent, slightly okay, completely novice developer, and could use feedback on coding practices, and/or areas where there is a built-in feature that would work better.

Code:

function AJAXForm(form, callback) {
this.form = form;
this.controls = [];
var self = this;
this.callback = callback;
this.submit = function(e) {
    e.preventDefault();
        var data = {};
        for (var i = 0; i < self.controls.length; i++) {
            var control = self.controls[i];
            data[control.name] = control.value;
        }
        if (self.form.method == "post") {
            $.post(self.form.action, data, self.callback);
        } else {
            $.get(self.form.action, data, self.callback);
        }
};

var getControls = function(obj) {
    for(var i = 0; i < obj.children.length; i++) {
        var control = obj.children[i];
        if(["INPUT", "SELECT", "TEXTAREA", "BUTTON"].includes(control.nodeName)) {
            self.controls.push(control);
            if(control.nodeName == "BUTTON" && control.type == "submit") {
                var submit = self.submit;
                $('#' + control.id).click(submit);
            }
        } else {
            getControls(control);
        }
    }
};

this.getControls = function() {
    this.controls = [];
    getControls(this.form);
};

this.toggleMethod = function() {
    this.form.method = (this.form.method == "get")? "post" : "get";  
    return this.form.method;
};

this.method = function(method) {
    if(method == "GET" || method == "POST") {
        this.form.method = method;
        return this;
    } else {
        return this.form.method;
    }
};

this.url = function(url) {
    if(typeof url == "string") {
        this.form.action = url;
        return this;
    } else {
        return this.form.action;
    }
};

this.getControls();
}

You create an AJAX form with var myAJAXForm = new AJAXForm(form, callback);.

example:

var form = document.getElementsByTagName("form")[0];
var callback = function(msg) {
    $('#display').text(msg);
};
var myAJAXForm = new AJAXForm(form, callback);
\$\endgroup\$
  • \$\begingroup\$ Could you give a more detailed example of how it is to be used? \$\endgroup\$ – 200_success Aug 7 '16 at 4:24
  • \$\begingroup\$ @200_success it uses the method and action attributes of the form element itself, auto grabs all of the controls, and ties its own submit function to all button[type=submit]'s in the form. the callback is used as the callback for the ajax request. \$\endgroup\$ – Null Spark Aug 7 '16 at 4:27

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.