Componette

Componette

vojtech-dobes

vojtech-dobes / nette.ajax.js 2.3.0

Flexible AJAX for Nette Framework. Supports snippets, redirects etc.

For Nette Framework

Flexible utility script for AJAX. Supports snippets, redirects etc.

License

MIT

Dependencies

jQuery 1.7

Installation

  1. Copy nette.ajax.js to your directory with Javascript files (you can use Bower for this).
  2. Link the file in your templates (usually in app/@layout.latte, after jQuery!).
  3. Put somewhere the initialization routine:
$(function () {
	$.nette.init();
});

Usage

By defaults all links and forms with CSS class ajax will be instantly ajaxified. Behavior can be altered in configuration of init extension. Object returned by call var init = $.nette.ext('init'); has these props:

name default value description
linkSelector a.ajax CSS selector for links
formSelector form.ajax CSS selector for forms
buttonSelector input.ajax[type="submit"], input.ajax[type="image"] CSS selector for form elements responsible for submit

Ajaxification is bound to click (submit) event in nette namespace. Ajaxification of specific link can be canceled with code like this (while other callbacks will remain):

$('a.no-ajax').off('click.nette');

Or even simpler:

$('a.no-ajax').netteAjaxOff();

Extensions

Ajaxification envelopes standard $.ajax() call and extends it with several events, that can be hooked with custom callbacks. Set of associated callbacks is called extension. Snippets processing, ability to cancel running request by Escape... all this functionality is implemented in form of extensions. Registration of extension looks like this:

$.nette.ext('name', {
    event1: function () {
    },
    event2: ...
}, {
    // ... shared context (this) of all callbacks
});

First argument is name. It's optional.

Second argument should be hash of callbacks with keys corresponding to names of events. These events are available:

name arguments description
init Called just once during $.nette.init(); call.
load requestHandler Should contain ajaxification. requestHandler can be bound to UI events to initiate AJAX request.
before jqXHR, settings Called immediatelly before AJAX request execution. If FALSE is returned, request won't start.
start jqXHR, settings Called immediatelly after start of AJAX request.
success payload, status, jqXHR, settings Called after successful completion of AJAX request. Equivalent to $.ajax( ... ).done( ....
complete jqXHR, status, settings Called after every AJAX request completion. Equivalent to $.ajax( ... ).always( ....
error jqXHR, status, error, settings Called in case of failure of AJAX request. Equivalent to $.ajax( ... ).fail( ....

Extension can be disabled:

$.nette.ext('name', null);

Extension can be configured. Its context can be acquired by:

var context = $.nette.ext('name');

Default extensions

name description
validation Limits the ajaxification to clicks/submits without Ctrl, Alt or Shift key, local links and valid form submits.
forms Adds support for submitting forms with all data, name of clicked button and coordinates of click in [type=image] inputs.
snippets Updates DOM by snippets array in response (default Nette handling of Latte snippets).
redirect Executes redirect to different URL (when $this->redirect() is called in presener). Can be replaced by history extension.
unique Keeps only request running at the same moment.
abort Allows user to abort running request by pressing Escape.
init Default ajaxification.

Useful tricks

All these special features expect all default extensions to be on.

data-ajax-off

Link or any other ajaxified element can have custom data attribute data-ajax-off. It contains names of extensions, that should be deactivated for Ajax request fired on element.

<a n:href="do!" class="ajax" data-ajax-off="snippets">

You can also use it in $.nette.ajax(). Like this:

$.nette.ajax({
	url: ...,
	off: ['snippets']
});

data-ajax-pass (in validation extension)

Ajaxification of element ensures, that e.preventDefault() will be called. This attribute can prevent it, if you need more callbacks to be fired.

data-ajax-append (in snippets extension)

New content of snippet with this attribute won't replace the old content, but it will rather be appended to it.

data-ajax-prepend (in snippets extension)

New content of snippet with this attribute won't replace the old content, but it will rather be prepended to it.

data-ajax-validate (in validation extension)

Click on link or submittion of form is validated on various conditions. You can switch any of them:

<a n:href="do!" class="ajax" data-ajax-validate='{"keys":false}'>

And as in case of data-ajax-off, you can pass it right into $.nette.ajax().

$.nette.ajax({
	url: ...,
	validate: {
		keys: false
	}
});

This means that clicking link with Ctrl will not open new tab, but will ajaxify request.

Dependency on other extension

In event callbacks, you can call this.ext() to get context of other extension. If you add true as second argument, script will fail if that extension won't be available.

$.nette.ext({
	success: function (payload) {
		var snippets = this.ext('snippets', true);
		...
	}
});
  • 2.3.0 Released version 2.3.0

    • Fixed compatibility with Nette Forms 2.3 and older (thx @PingusPepan)
    • Fixed bug when passing absolute URL with port number (thx @iguana007)
    • Bower nette.ajax.js doesn't depend on nette-forms anymore
  • 2.2.0 Released version 2.2.0

    • Added support for validation scope in forms (thx to @xificurk)
    • Default configuration of validation extension can be globally changed
    • Enabled installation via npm install nette.ajax.js (thx to @ondrs)
    • Fixed error on ajaxified form without method (thx to @Ciki) & action (thx to @enumag)
    • Fixed compatibility with Nette Forms 2.4 (thx to @venca-x)
    • Snippet's content gets always placed if it contains <script> element (thx to Jakub Patocka)

    Example of validation defaults configuration:

    $.nette.ext('validation').validation.keys = false; // also clicks with Cmd/Ctrl will be ajaxified
    
  • 2.1.0 Released version 2.1.0

    • $.nette.ajax() now supports first argument to be URL (thus becoming more similar to $.ajax())
    • Bower installs also extensions.
    • Content of snippet is replaced with $el.html(...) only if new content differs from the previous one.
  • 2.0.0 Released version 2.0.0

    Improvements:

    • history.ajax.js extension extracted to separate repository
    • nette.ajax.js can be installed as Bower package

    Features:

    • added support for Ajax file uploads
    • added support for data-ajax-prepend data attribute (similar to data-ajax-append)

    Bugfixes:

    • form validation works nicely with nette.ajax.js in IE 8 (#75)
  • 1.2.3 Released version 1.2.3

    Here is the list of fixed issues:

    Thanks to all reporters and contributors!

  • 1.2.3-RC1 1.2.3 RC1

    Same as stable version 1.2.3.

  • 1.2.2 Released version 1.2.2

    • added new method for removing ajaxification from any elements
    $('.foo').netteAjaxOff();
    • added default selector for <button type=submit class=ajax>

    There are also 3 new extensions:

    • confirm.ajax.js for simple confirmation questions via [data-confirm] attribute
    • ga.ajax.js outlining the way how to use Google Analytics with history.ajax.js extension
    • fidRemove.ajax.js for silent removal of _fid parameter from URL

    Also automatic call of load on successful request is no longer registered in init extension, but in load extension.

  • 1.2.1 Released version 1.2.1

    • added new event prepare in request's lifecycle (triggered before before)
    • added support for infinite scrolling
    <ul n:snippet="foo" data-ajax-append>
        <li n:foreach="$articles as $article">
            {$article->title}
        </li>
    </ul>
    • events success, error and complete receive same arguments as in normal $.ajax() call
    • new API for more precise work with snippets
    $.nette.ext('snippets').before(function ($el) {
        // příležitost k odvázání událostí a dalšího smetí...
    });
    $.nette.ext('snippets').after(function ($el) {
        // ... a v již aktualizovaném snippetu možnost navázat haraburdí nové
    });
  • 1.2.0 Released version 1.2.0

    • new support for History API (from HTML 5)
    $configurator->onCompile[] = function ($configurator, $compiler) {
        $compiler->addExtension('ajax', new VojtechDobes\NetteAjax\Extension);
    };
    • dependencies among extensions can be optional
    • returned support for native beforeSend option
    • adding data-ajax-pass to ajaxified element will prevent killing the original event
    • fixed compatibility with $form->addDynamic()

    There is also change in events API:

    • beforeSend now triggers before event
    • start event is called immediately after start of the request
    • return value of start callback loses any meaning
    • events before and start receive same arguments: jqXHR, settings
  • 1.1.2 Released version 1.1.2

    • added support for anonymous extensions (name is optional as first argument)
    $.nette.ext({
        load: function () { ...
    });
    • extensions can be turned off per specific AJAX request
    $.nette.ajax({
        off: ['snippets']
    }, this, e);
    <a n:href="foo!" class="ajax" data-ajax-off="snippets">Do something.</a>
    • added new jQuery shortcut method .netteAjax() for calling request directly on element
    $('#element').click(function (e) {
        $(this).netteAjax(e, { ... }).done(function () { ... });
    });
    • setValidationScope(FALSE) called on form is now respected
    • forms returned via snippets are automatically enhanced by client validation
    • fixed unique extension
  • 1.1.0 Released version 1.1.0

    • extensions can be added, turned off or retrieved for further modifications after $.nette.init()
    • extensions' event callbacks cannot be retrieved or modified anymore
  • 1.0.1 Released version 1.0.1

    • added missing default selector for <input type=image class=ajax>
    • fixed retrieval of click coordinates on image button
    • fixed compatibility with netteForms.js
bar-chart-fill

Statistics

download-cloud-fill
N/A
star-fill
150
bug-fill
35
flashlight-fill
2y
price-tag-2-line

Badges

Componette Componette felix@nette.org