Use Ajax

Without JavaScript

Domajax is a free jQuery plugin that give you tools to add ajax calls within your application, without a piece of javascript. It uses HTML5's data- attribute, and jQuery's .on() method to handle your ajax interactions.

How does it work ?

A classic ajax call is made this way :
  • A user fills a form and post it to an endpoint that will process that form
  • Endpoint validates and saves data, and prepares a response
  • The response is put inside a container, such as a div, to be seen by user
Using domajax, those requirements are specified inside the dom.
  • Endpoint is set inside data-endpoint attribute
  • Input container (where are input fields) is set inside data-input attribute
  • Output container (where to put the response) is set inside data-output attribute
  • Finally, domajax is automatically launched if domajax click is put on the class attribute
Of course, this is the basic usage of domajax, it can be triggered on keyup and on change and other events if you wish. There is also a lot of built-in options, such as auto-lock on the input fields (to avoid double-posting), data replacements and toggles (used for example to put a nice wait gif when your ajax calls are processing), and callbacks for more flexibility.
A basic ajax call

All demonstrations are loaded inside iframe tags so you can see their source code easily. While validating an ajax form, it is possible that the response appears outside the iframe. Just click "resize" below each examples to make the iframe size fit to its contents.

This form looks like this:


<div id="inputs">
    <label for="name">Enter your name</label>
    <input type="text" id="name" name="name" value="Mike"/>
    <br/>
    <input
            type="button"
            value="Send"
            class="btn domajax click"
            data-endpoint="introduction-handler.php"
            data-input="#inputs"
            data-lock="#inputs"
            data-output="#output"
            />
</div>

<div id="output"></div>

This form looks like this:


<form id="input" action="#" method="post">

    <label>Gender :</label>
    <label class="radio">
        <input name="gender" type="radio" value="Male" checked/> Male
    </label>
    <label class="radio">
        <input name="gender" type="radio" value="Female"/> Female
    </label>

    <label>First Name :</label>
    <input name="first-name" type="text" value="Mickael"/>

    <label>Last Name :</label>
    <input name="last-name" type="text" value="Steller"/>

    <label>Language :</label>
    <select name="language">
        <option value="en">English</option>
        <option value="fr">French</option>
        <option value="cn">Chinese</option>
    </select>

    <label>Message :</label>
    <textarea name="message">Hello, world!</textarea>

    <label class="checkbox">
        <input name="steak" type="checkbox"/> I like steaks
    </label>

    <br/>

    <input
            type="button"
            value="Submit"
            class="btn domajax click"
            data-endpoint="input-classic-form-handler.php"
            data-input="#input"
            data-output="#output"
            />

</form>

<div id="output"></div>

This form looks like this:


<label for="name">Enter your name and press enter</label>
<input
        type="text"
        id="name"
        value="Mike"
        class="domajax change"
        data-endpoint="input-self-handler.php"
        data-input=""
        data-output="#output"
        />

<div id="output"></div>

This form looks like this:


<input
        type="button"
        value="Get the time"
        class="btn domajax click"
        data-endpoint="output-json-clock-handler.php"
        data-output="#output"
        data-output-json="year month day hour min sec"
        data-json-year="#year-container"
        data-json-month="#month-container"
        data-json-day="#day-container"
        data-json-hour="#hour-container"
        data-json-min="#min-container"
        data-json-sec="#sec-container"
        />

<br/><br/>

<span id="day-container" style="color: blue">??</span> /
<span id="month-container" style="color: green">??</span> /
<span id="year-container" style="color: red">????</span> &nbsp;
<span id="hour-container" style="color: orange">??</span> :
<span id="min-container" style="color: pink">??</span> :
<span id="sec-container" style="color: yellow">??</span>

<br/><br/>

<p>Raw output:</p>

<div id="output"></div>

This form looks like this:


<form id="input" action="input-classic-form-handler.php" method="post" target="_blank">

    <label>Some text :</label>
    <input name="sample-text" type="text" value="Hello, world!"/>

    <label class="checkbox">
        A checkbox
        <input name="sample-check" type="checkbox"/>
    </label>

    <label>A select :</label>
    <select name="sample-select">
        <option value="Paris">Paris</option>
        <option value="Nantes">Nantes</option>
        <option value="Bordeaux">Bordeaux</option>
    </select>

    <label>Radio buttons</label>
    <label class="radio inline">
        <input name="sample-radio" type="radio" value="Foo" checked/> Foo
    </label>
    <label class="radio inline">
        <input name="sample-radio" type="radio" value="Bar"/> Bar
    </label>

    <label>A textarea</label>
    <textarea name="sample-textarea">Foo, bar!</textarea>

    <label>An hidden field</label>
    <input name="sample-hidden" type="hidden" value="Hidden data"/>

    <label>A read-only field</label>
    <input name="sample-readonly" type="text" value="Readonly data" readonly/>

    <label>A disabled field</label>
    <input name="sample-disabled" type="text" value="Disabled data" disabled/>

    <br/>

    <input
            type="button"
            value="Send using domajax"
            class="btn domajax click"
            data-endpoint="lock-form-handler.php"
            data-lock="#input"
            data-input="#input"
            data-output="#output"
            />

</form>

<div id="output"></div>

This form looks like this:


<div id="inputs">

    Do you want the server to send a 500 error (so the ajax call will fail)?

    <br/><br/>

    <input type="radio" name="want_error" value="yes"/> Yes
    &nbsp;&nbsp;
    <input type="radio" name="want_error" value="no" checked/> No

    <br/><br/>

    <input
            type="button"
            value="Go"
            class="btn domajax click"
            data-endpoint="highlight-succerror-handler.php"
            data-input="#inputs"
            data-highlight-success="#success"
            data-highlight-failure="#failure"
            />

    <br/><br/>

    <div id="success">This text will be highlighted if the ajax call succeed</div>
    <div id="failure">This text will be highlighted if the ajax call fails</div>

</div>

This form looks like this:


<div id="inputs">

    Do you want the server to send a 500 error (so the ajax call will fail)?

    <br/><br/>

    <input type="radio" name="want_error" value="yes"/> Yes
    &nbsp;&nbsp;
    <input type="radio" name="want_error" value="no" checked/> No

    <br/><br/>

    <input
            type="button"
            value="Go"
            class="btn domajax click"
            data-endpoint="highlight-color-succerror-handler.php"
            data-input="#inputs"
            data-highlight="#hello"
            data-highlight-color-success="green"
            data-highlight-color-failure="red"
            />

    <br/><br/>

    <div id="hello">This text will be highlighted according to the ajax call status</div>

</div>

This form looks like this:


<input
        type="button"
        value="Click me to get the time"
        class="btn domajax click"
        data-endpoint="callback-basic-handler.php"
        data-callback-success="alert_time"
        />

<script type="text/javascript">

    function alert_time(elem, response, textStatus, jqXHR) {
        alert(response);
    }

</script>

This form looks like this:


<input
        type="button"
        value="Click me to receive some alerts..."
        class="btn domajax click"
        data-endpoint="script-alert-handler.php"
        data-script-before="alert('Ajax call will begin.');"
        data-script-success="alert('Ajax call has succeeded! Result is ' + response);"
        />

This form looks like this:


<input
        type="button"
        value="Run"
        class="btn domajax click"
        data-endpoint="domajax-progress-handler.php"
        data-domajax-not-empty=""
        data-output="#percent"
        data-delay="1000"
        data-script-empty="$('#percent').html('--'); return false;"
        />

<div>
    Progression :
    <span id="percent">--</span>
    %
</div>

This form looks like this:


<label for="insert">Enter an element</label>
<input type="text" id="insert" name="insert"/>
<br/>
<input
    type="button"
    value="Store"
    class="btn domajax click"
    data-endpoint="raw-rest-handler.php"
    data-method="put"
    data-raw="#insert"
    data-output="#contents"
    />

<br/><br/>

<div id="contents">
    <?php include "raw-rest-handler.php"; ?>
</div>

This form looks like this:


<label class="checkbox inline no_indent">
    <input
            type="checkbox"
            id="hello"
            value="world"
            class="btn domajax change"
            data-endpoint="event-change-tick-handler.php"
            data-input=""
            data-output="#output"
            /> Click me!
</label>

<div id="output"></div>

This form looks like this:


<label for="nickname">Enter a Mario Bros character's name</label>

<input
        type="text"
        id="nickname"
        name="nickname"
        value=""
        class="domajax keyup"
        data-endpoint="event-keyup-nickname-handler.php"
        data-input=""
        data-output="#availability-icon"
        />

<span id="availability-icon"><i class="icon-remove"></i></span>

This form looks like this:


<div id="inputs">
    <label for="name">Enter your name</label>
    <input type="text" id="name" name="name" value="Mike"/>
    <br/>
    <input type="button" id="send" class="btn" value="Send" />
</div>

<div id="output"></div>

<script type="text/javascript">

    $('#send').click(function() {
        $(document).domAjax({
            endpoint: 'manual-usage-classic-handler.php',
            input: '#inputs',
            lock: '#inputs',
            output: '#output'
        });
    });

</script>

Easy integration with frameworks

Modern applications are built using frameworks, and interfaces are created with real-time posting for better user experiences. This mean, always more interactions, more code and more complexity.

Using the dom for such jobs make things clear:

  • There is no need to find where is written javascript for a specific input.
  • There is no need to access element ids, potentially hard to get within a framework.
  • The required html code is easy to read and easy to maintain.
  • This is very quick to code new ajax interactions.
  • New ajax interactions can be added on the fly, even being part of an ajax response.
And more with domajax:
  • A container is not necessarily a form tag.
  • Inputs can be an entire form, a single field or even an html container such as a div.
  • A lot of options are available, common ajax requirements are covered.

// Symfony2 example
{{
    form_widget(SearchForm.someFilter, {
        'attr': {
            'class': 'domajax click',
            'data-endpoint': path('search_click_some_filter'),
            'data-input': '',
            'data-output': '#searchResults',
            'data-lock': '',
        }
    })
}}

            

Get started

Download

Domajax can work standalone with jquery, but it is recommanded to use jquery-ui and json2.js for full functionalities and better compatibility.
  • Download the latest domajax version on GitHub
  • Download jQuery, domajax has been tested with jQuery >= 1.7.0
  • Download jQuery UI (optional) if you want to use data-highlight option (which uses .animate() on colors).
  • Download json2.js or json3.js (optional) for a better domajax compatibility with exotic browsers, such as IE7, Safari2 and so on.

Install

After downloading all scripts listed above, put and uncompress them in your poject, for example in a js directory.

KolyMac:domajax-starter ninsuo$ ls -l js
total 272
-rw-r--r--@ 1 ninsuo  staff  95786 Jun 16 17:49 jquery-1.11.1.min.js
drwxr-xr-x@ 6 ninsuo  staff    204 Jun 16 17:50 jquery-ui-1.10.4
-rw-r--r--  1 ninsuo  staff  31167 Jun 16 17:49 jquery.domajax.js
-rw-r--r--@ 1 ninsuo  staff   8143 Jun 16 17:45 json3.min.js

Then, create a demo.php file, and load all javascripts and css.

<?php

   // here all your php code

?>
 <!DOCTYPE html>
<html lang="en">
    <head>
        <meta http-equiv="content-type" content="text/html; charset=utf-8"/>
        <link href="js/jquery-ui-1.10.4/css/ui-lightness/jquery-ui-1.10.4.min.css" rel="stylesheet" media="screen">
        <title>My First Domajax Call!</title>
    </head>
    <body>

        <!-- here all your html code -->

        <script src="js/json3.min.js"></script>
        <script src="js/jquery-1.11.1.min.js"></script>
        <script src="js/jquery-ui-1.10.4/js/jquery-ui-1.10.4.min.js"></script>
        <script src="js/jquery.domajax.js"></script>
    </body>
</html>

Use

You are now ready! Let's write a Hello, world! example.

Replace // here all your php code by :

if (array_key_exists('name', $_POST)) {
	echo "Hello, ", htmlentities($_POST['name']), " !";
	die();
}

Replace <!-- here all your html code --> by :

Enter your name:
<input id="name" type="text" />
<button class="domajax click" data-endpoint="demo.php" data-input="#name" data-output="#output">Send</button>
<div id="output"></div>

And here you go.

There are 90 other demonstrations available in this documentation.

License

Domajax is released in the same way as jQuery fundation projects.

Source code

Domajax is released under the terms of the MIT license.

The MIT License is simple and easy to understand and it places almost no restrictions on what you can do with domajax.

You are free to use domajax in any project (even commercial projects) as long as the copyright header is left intact.

Sample code

All demos and examples, whether in a code project's repository or displayed on this website, are released under the terms of CC0.

CC0 is even more permissive than the MIT license, allowing you to use the code in any manner you want, without any copyright headers, notices, or other attribution.

Web site

Contents on domajax web site are released under the terms of the MIT license.


Table of contents

All the documentation at a glance

Domajax options

And more with domajax


About

I am Alain Tiemblo, a lazy and passionate web developer. I spend most of my life sleeping, eating, swimming and, of course, coding. I am living in Nantes (France), a nice and animated city close to the Atlantique ocean. I spend my vacations travelling, with a special attraction to China after being there 9 months already.

I enjoy being that lazy developer as I am always looking for ways to do more with less efforts and time. For me, but also and particularily for the users who will use my work. And I love searching for solutions to develop impossible stuffs, such as multi-threading simulation in PHP, user-friendly parsers, strong enconding matters, captcha-breakers and so on.

I began computer science at 13 years old, as an IRC chatter. I developped my first mIRC script because I seen a game robot that wasn't opensource, and wanted to put it on my own channels. This was the very beginning of an incredible adventure. I spent 8 years on IRC, coding games, moderation and administration robots, proxy to bypass school's firewall to chat during classes, chat client for mobile devices throught http, chat analytics and more.

After being gradulated from secondary school, I studied computer science at the European Institute of Technology, a 5-years course that creates self-learner nerds. During first 2 years, it was forbidden to use existing libraries: if we required a function (whichever one), we needed to code it! A nice way to learn a lot of low-level stuffs, and to understand how things run. The other years covered a large variety of technologies, from langages, system and network administration, to technical topics such as code parsing, network development, computer graphics, artificial intelligence and so on. Coupled with internships and international studies, the many things I learnt made me able to choose THE job I'm made for: web developer.

I am also a Zend Certified Engineer, who done the examination just for fun.

You can find some of my geeky activity on Stackoverflow:

profile for Ninsuo on Stack Exchange, a network of free, community-driven Q&A sites

Alain Tiemblo