DRY ajax forms - JSFiddle

ajax call

by oktaviardi pratama

HTML

<p class="js-result"></p>
<form action="/echo/jsonp" data-remote="true" data-type="json" data-callback="submitEmail">
    <h3>Submit mail</h3>
    <input type="text" name="name" value="Kasper"/>
    <input type="email" name="email" value="[email protected]"/>
    <input type="submit" name="submit" value="submit"/>
</form>

<form action="/echo/jsonp" data-remote="true" data-type="json" data-callback="newSubscription">
    <h3>Subscribe</h3>
    <input type="email" name="email" value="[email protected]"/>
    <input type="submit" name="submit" value="submit"/>
</form>

JavaScript

var App = {
    ajaxRequests: {
        submitEmail: function(response) {
            $('.js-result').text('Thanks, ' + response.name);
        }, 
        newSubscription: function(response) {
            $('.js-result').text('Confirmation sent to: ' + response.email);
        }   
    },
    
    init: function() {
        this.DRYForms('[data-remote]');
    },
    
    DRYForms: function(forms) {
        $(forms).on('submit', function() {
            var form = $(this);
            $.ajax({
                type: form.attr('method') || 'GET',
                url: form.attr('action'),
                data: form.serialize(),
                dataType: form.data('type') || 'json',
                success: function(res) {
                    App.ajaxRequests[form.data('callback')].apply(App, arguments);
                }
            });
            return false;
        });
    }
};

App.init();