avcwmw
Last Updated: February 25, 2016
·
1.109K
· idered

DRY Ajax forms

Sending forms with ajax is simple especialy with library like jQuery, thought if you're going to use ajax a lot on your website, it would be good to think a little about DRY solution. Here's mine solution:

HTML

<p class="js-result"></p>
<form action="/send-mail" 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="kasper@example.com"/>
    <input type="submit" name="submit" value="submit"/>
</form>

As you can see, I've used data attributes:

  • data-remote - all forms with this attribute will be send with ajax
  • data-type - type of response (optional)
  • data-callback - function that is triggered after submission

JS

var App = {
    ajaxRequests: {
        submitEmail: function(response) {
            $('.js-result').text('Thanks, ' + response.name);
        }   
    }

};

$('[data-remote]').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() {
            App.ajaxRequests[form.data('callback')].apply(App, arguments);
        }
    });
    return false;
});

You can see cool preview on jsfiddle

View extended version in my framework