Last Updated: May 31, 2021
· 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:


<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=""/>
    <input type="submit" name="submit" value="submit"/>

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


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


$('[data-remote]').on('submit', function() {
    var form = $(this);
        type: form.attr('method') || 'GET',
        url: form.attr('action'),
        data: form.serialize(),
        dataType:'type') || 'json',
        success: function() {
            App.ajaxRequests['callback')].apply(App, arguments);
    return false;

You can see cool preview on jsfiddle

View extended version in my framework